解决INSERT INTO语句的语法错误

时间:2014-03-21 14:51:55

标签: php mysql sql syntax-error

当我尝试将数据输入到表单中时出现此错误:

  

“错误:您的SQL语法中出现错误//请查看手册   对应于您使用的//正确语法的MySQL服务器版本   'Order(Name,Address,Credit_card_number,Product_id,   // Delivery_method)VALUES'在第1行“

我一遍又一遍地检查了数据库名称,表名和属性名称,我找不到问题。

这是我添加到数据库的表单:

<html>
<body>

<form action="insert.php" method="post">
  <p>Name:
    <input type="text" name="name">
  </p>
  <p>Address:
    <input type="text" name="address">
  </p>
  <p>Credit Card Number: 
    <input type="text" name="credit_card_number">
  </p>
  <p>Product Order ID: 
    <input type="text" name="product_id">
  </p>
  <p>Delivery Method: 
    <input type="text" name="delivery_method">
  </p>
  <p>
    <input type="submit">
  </p>
</form>

</body>
</html>

这是我的insert.php文件:

<?php
$con=mysqli_connect("localhost","root","","order_page");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

$sql="INSERT INTO Order (Name, Address, Credit_card_number, Product_id, Delivery_method)
VALUES 
('$_POST[name]','$_POST[address]','$_POST[credit_card_number]','$_POST[product_id]','$_POST[delivery_method]')";

if (!mysqli_query($con,$sql))
  {
  die('Error: ' . mysqli_error($con));
  }
echo "1 record added";

mysqli_close($con);
?>

2 个答案:

答案 0 :(得分:4)

ORDER是MySQL中的reserved keyword。如果您要命名一个表ORDER,则在使用它时必须将其包装在刻度线中:

$sql="INSERT INTO `Order` (Name, Address, Credit_card_number, Product_id, Delivery_method)
VALUES  ('$_POST[name]','$_POST[address]','$_POST[credit_card_number]','$_POST[product_id]','$_POST[delivery_method]')";

仅供参考,您对SQL injections

持开放态度

答案 1 :(得分:0)

$sql="INSERT INTO Order (Name, Address, Credit_card_number, Product_id, Delivery_method)
VALUES 
('$_POST[name]','$_POST[address]','$_POST[credit_card_number]','$_POST[product_id]','$_POST[delivery_method]')";

应该是

$name=$_POST['name'];
$address=$_POST['address'];
$credit_card_number=$_POST['credit_card_number'];
$product_id=$_POST['product_id'];
$delivery_method=$_POST['delivery_method'];

$sql="INSERT INTO `Order` (Name, Address, Credit_card_number, Product_id, Delivery_method)
VALUES 
('$name','$address','$credit_card_number','$product_id','delivery_method')";

确保使用占位符防止SQL注入