0

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?

1
  • If you have a SQL error, the best approach is usually to output the query you are trying to execute and try it "dry" in a SQL worksheet (such as that in phpMyAdmin); if it doesn't work there either, your problem is in the SQL domain and you can discount the PHP and connection stuff clouding the issue. Commented Aug 5, 2010 at 19:42

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

2 Comments

Note that you won't be able to use mysql_real_escape_string() until the connection to the DB is made.
Its best if you can work with a framework or at the very least a wrapper function to deal with your SQL injections.
0

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) . "')";

2 Comments

Sorry, I don't know what you mean
and now pray that "condition" will never become a reserved keyword in mysql ;-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.