Mysql语法错误 - Backtics无法解决它

时间:2012-11-20 16:27:04

标签: mysql syntax

我正在用PHP编译查询以在db:

中插入产品
$query = "";

if ($A > 0) {$query .="INSERT INTO ped_prod (`ped_id`, `prod_id`, `cant`) VALUES ($last_id, 1, $A); ";}

if ($B > 0) {$query .="INSERT INTO ped_prod (`ped_id`, `prod_id`, `cant`) VALUES ($last_id, 2, $B); ";}

if ($C > 0) {$query .="INSERT INTO ped_prod (`ped_id`, `prod_id`, `cant`) VALUES ($last_id, 3, $C); ";}

通过mysql_query($prodquery, $conexion)运行查询时出现以下错误:

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
'INSERT INTO ped_prod (`ped_id`, `prod_id`, `cant`) VALUES (13, 3, 2)' at line 1

我试过了:
- 交换引号('),双引号(“)和反引号(`)
- 检查MySQL保留字列表
- 在PHPmyAdmin中运行查询(它表示'#1受影响的行',但它将数据加载到表中,而在浏览器中执行脚本时不是这种情况)

我错过了什么?提前谢谢!

1 个答案:

答案 0 :(得分:1)

mysql_query()一次只支持一个查询。请参阅respective PHP docs

  

mysql_query()向与指定link_identifier关联的服务器上的当前活动数据库发送唯一查询(不支持多个查询)。

因此,在您的情况下,只需单独运行每个INSERT语句,您应该没问题。

另一个选项,因为所有插入都是相似的,将通过连接值子句来连接它们:

$values = array();
if ($A > 0) {$values[] ="($last_id, 1, $A)";}

if ($B > 0) {$values[] ="($last_id, 2, $B)";}

if ($C > 0) {$values[] ="($last_id, 3, $C)";}

// echo query if needed
if ( count( $values ) > 0 ) {
  $queries = 'INSERT INTO ped_prod (`ped_id`, `prod_id`, `cant`) VALUES ' . implode( ',', $values );

  // execute query
  //  ...
}

此外,不推荐使用mysql_X函数。切换到PDOmysqli