在 SQL 语法和 PHP 中获取错误


Getting error in SQL syntax and PHP

我收到以下错误,无法弄清楚问题是什么。

错误

:您的SQL语法有错误;请查看与您的MySQL服务器版本相对应的手册,了解在第1行的"订单(订单ID,客户ID,产品ID,品牌,型号,价格,金额,总成本)V"附近使用的正确语法

//connect to database
$connection = mysql_connect("localhost","root","") or die ("Can't connect");
mysql_select_db("shoppingcart", $connection) or die ("Can't connect");
//get order id
$vol = mysql_query("SELECT orderid FROM ordertracking WHERE email='$email'");
while($volume=mysql_fetch_array($vol)) {
  $orderid = $volume['orderid'];
}
echo $orderid;
// add new order
$order = "INSERT INTO order (orderid, customerid, productid, brand, model, price, amount, totalcost) VALUES ('$orderid', '$customerid', '$productid', '$brand' , '$model', '$price', '$amount', '$totalcost')";
if (!mysql_query($order,$connection)) {
  die('Error: ' . mysql_error());
  echo "Sorry, there was an error";
}
echo "New order added" . "<br />";
mysql_close($connection);

ORDER是一个 mysql resered 单词,将其括在反引号 '' 中。

您不应该有与 mysql 保留字冲突的表或列名称,否则您必须将它们括在反引号中。

$order = "INSERT INTO `order` (orderid, customerid,...

像这样:

插入到"订单"(...(备选方案+7)

如果这解决了问题,请将功劳归功于Shakti Singh。

关键字 ORDER 是 sql 中的保留关键字。意味着你不能使用它

所以这将产生一个错误:

$order = "INSERT INTO order (orderid, customerid, productid, brand, model, price, amount, totalcost) VALUES ('$orderid', '$customerid', '$productid', '$brand' , '$model', '$price', '$amount', '$totalcost')";

插入到订单中

上述语句中的顺序应该在反引号中(如 shakti 所述)喜欢

插入到"订单"(订单 ID,......

或者您可以将保留关键字括在方括号中,例如

插入到 [订单] (订单 ID,......

有关更多信息,请查看此线程堆栈溢出问题

其他事情是 die 之后的任何代码都不起作用,我的意思是:

if (!mysql_query($order,$connection)) {
 die('Error: ' . mysql_error());
 echo "Sorry, there was an error";}

此代码

echo "Sorry, there was an error";

将不起作用。并使用以下代码:

die('Error: ' . mysql_error());

出于安全原因,根本不建议使用