简体   繁体   中英

Error when inserting into SQL table with PHP

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM