Inserting data into SQL table from HTML form
Solution 1
You should change:
if(!con){
echo 'Not connected to server!';
}
to:
if(!$con){
echo 'Not connected to server!';
}
as you're missing a dollar sign there.
Additionally, you're using a mysql_
function here, on the mysqli_
object $con
:
if(!mysql_query($con,$sql))
Change this to
if(!mysqli_query($con,$sql))
SQL injection
As your query is vulnerable to SQL injection, then I'd like to recommend you take a look at using prepared statements, or using mysqli_real_escape_string()
-- though, this comes with a few gotcha's: https://stackoverflow.com/a/12118602/7374549
Solution 2
You have done two small mistakes ie
1) forgot to add $
before the variable name ie changes is
if(!$con){
echo 'Not connected to server!';
}
2) you are connected with mysqli_connect
but you are trying to use mysql_query
functions in it. so please change and use mysqli_query
if(!mysqli_query($con,$sql)){ }
This is issue in your case. My suggestion is to use mysqli
or PDO
that is good practice.
Asad Hussain
Updated on June 04, 2022Comments
-
Asad Hussain almost 2 years
A HTML form has been created that should (when filled) send the data it's holding to a database inserting a new row so it can be used later on. However, I can't seem to get it to work, I'm getting the following error:
Notice: Use of undefined constant con - assumed 'con' in C:\xampp\htdocs\form\insert.php on line 4
Warning: mysql_query() expects parameter 1 to be string, object given in C:\xampp\htdocs\form\insert.php on line 17
Data not inserted
HTML Code
<!DOCTYPE html> <html> <head> <title>Form linked to database</title> </head> <body> <form action="insert.php" method="post"> Name: <input type="text" name="username"> <br> Email: <input type="text" name="email"> <br> <input type="submit" value="insert"> </form> </body> </html>
PHP Code
<?php $con = mysqli_connect('localhost','[retracted]','[retracted]'); if(!con) { echo 'Not connected to server!'; } if(!mysqli_select_db($con,'tutorial')) { echo 'Database not selected!'; } $Name = $_POST['username']; $Email = $_POST['email']; $sql = "INSERT INTO person (Name,Email) VALUES ('$Name','$Email')"; if(!mysql_query($con,$sql)) { echo 'Data not inserted'; } else { echo 'Data inserted'; } //header("refresh:2; url=form.html"); ?>
I'm new to PHP and followed the following YouTube tutorial.
I'm also using XAMPP for this, on a localhost. Any help is appreciated. Thank you.
-
Twinfriends about 7 yearsNice copy paste from W3. At least you editet de standard names. But it won't help the OP, since he's trying to insert data from a HTML form. If you copy paste, then please copy paste an example with prepared statements for a good example.
-
Sujal Patel about 7 yearsThis is just insert query example. i think he's not find in w3.