sosytee
sosytee

Reputation: 1277

Data is not inserted into database

I would like to add data from an html form into the database , here is my code

<html><?php

$var1=$_POST[tag];
$var2=$_POST[name];
$var3=$_POST[surname];

echo $var1;
echo $var2;
echo $var3;

$dbhandle=mysql_connect('localhost','root','mysql')
or die ("Unable to connect to database");
 mysql_select_db("arduino");

mysql_query("INSERT INTO door('Tag','Name','Surname') VALUES('$var1','$var2','$var3')");
?>
</html>

However, none of the data enters the database, i have put the echo statements so as to show that data from the form is received and it all works fine, but when i open the db,

select * from door

returns empty set.

Upvotes: 2

Views: 98

Answers (3)

Mr. Alien
Mr. Alien

Reputation: 157414

You have quotes around your column names, so remove those

//Tag,Name,Surname

mysql_query("INSERT INTO door(Tag,Name,Surname) VALUES('$var1','$var2','$var3')");

                          ---^----^---^------^---

Note: Your code is vulnerable to SQL injection, also mysql_() API is now deprecated as of > PHP 5.5.0, consider using mysqli_() or PDO instead.

Read the big red box on php.net

enter image description here


You should always use error reporting in such cases, so if you are not going to use a different API, than use echo mysql_error($connection); which will give you a user friendly error message.

Upvotes: 4

Abdul Jabbar
Abdul Jabbar

Reputation: 5971

First of all i would not suggest you to use mysql but PDO or MySQLi. And your code is total vulnerable to attacks like sql injection and your db can be hacked easily. with PDO prepared statements you can use this as like

$pdoCon = new PDO('mysql:host=localhost;dbname=mydb', 'root', 'abc');
$stmt = $pdoCon->prepare("INSERT INTO door(Tag,Name,Surname) VALUES(?,?,?)");
$stmt->bindParam(1, $var1, PDO::PARAM_INT);
$stmt->bindParam(2, $var2, PDO::PARAM_STR, 20);
$stmt->bindParam(3, $var3, PDO::PARAM_STR, 20);
$stmt->execute();

it is total safe and much better to use and bet it will work like charm with no sql injection attack or any other. for more information read through http://www.php.net/pdo.prepared-statements

Upvotes: 0

vee
vee

Reputation: 38645

Remove single quotes ' from the column names in your query:

mysql_query("INSERT INTO door(Tag,Name,Surname) VALUES('$var1','$var2','$var3')");

If your intention is to escape the column names then mysql's escape character is back tick '`'. And they are only required if the column names or table names are one of the reserved words.

Upvotes: 2

Related Questions