views:

20

answers:

2

So this is my code:

function function() {
$isbn = $_REQUEST["isbn"];
$price = $_REQUEST["price"];
$cond = $_REQUEST["cond"];

$con = mysql_connect("localhost","my_usernam", "password");
if (!$con) die('Could not connect:' . mysql_error());
mysql_select_db("my_database",$con);

$sql="INSERT INTO 'Books' (isbn, price, condition)
VALUES ('$isbn','$price','$cond')";


if (!mysql_query($sql,$con))
 {
 die('Error: ' . mysql_error());
 }

mysql_close($con);
return "It works";

But when run it results in:

Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''Books' (isbn, price....

Anyone know why this is happening?

Thanks!

A: 

Wrap table names in backticks, not quotes, and make sure to escape your input for security:

$sql="INSERT INTO `Books` (`isbn`, `price`, `condition`)
VALUES ('" . mysql_real_escape_string($isbn) . "',
      '" . mysql_real_escape_string($price) . "',
      '" . mysql_real_escape_string($cond) . "')";
Scott Saunders
Sorry, I don't know what you mean
Jake
I've added code to show you.
Scott Saunders
and now pray that "condition" will never become a reserved keyword in mysql ;-)
mvds
Excellent point mvds
Scott Saunders
Thanks Scott!!!
Jake
+3  A: 

You should use backticks instead of single quotes for table and field names:

$sql="INSERT INTO `Books` (`isbn`, `price`, `condition`)
    VALUES ('$isbn','$price','$cond')";

will work.

ps. to prevent all kinds of nasty security holes, escape the input fields with:

$isbn = mysql_real_escape_string($_REQUEST["isbn"]);
// etc etc for all fields
mvds
Awesome, thanks mvds! :)
Jake
Note that you won't be able to use mysql_real_escape_string() until the connection to the DB is made.
Scott Saunders
Excellent point Scott
mvds
Its best if you can work with a framework or at the very least a wrapper function to deal with your SQL injections.