SQL 中的事务已提交,但只有 1 个查询正确完成


transaction in SQL is committed but only 1 of the queries is done correctly

我有 2 个表,在一个表中,我想在特定行中增加一个计数器,同时在另一个表中插入。我正在使用php和MySQL,引擎是InnoDB。

这是我的代码:

function incrementCommentCounter ($id,$photoId,$text,$date) {
$query1= "UPDATE photos SET comments=comments+1 WHERE IdPhoto=$photoId";
//$query2= "INSERT INTO allComments (IdPhoto,IdUser,comment,date) VALUES ('%s',1,'%s',%s)";
//check if a user ID is passed
//if (!$id) errorJson('Authorization required');
mysql_query("START TRANSACTION");
$result1=mysql_query($query1);
$result2=mysql_query("INSERT INTO allComments (IdPhoto,IdUser,comment,dates) VALUES ('%s',1,'%s','%s')",$photoId,$text,$date);
if (!$result1 || !$result2) {
    mysql_query("ROLLBACK");
    errorJson($result2['error']);
} else {
    mysql_query("COMMIT");
    print json_encode(array('successful'=>1));
}

}

我做错了什么?

谢谢。

编辑:

修复了一些错别字。现在,第二个查询永远不会正确执行,因此不会执行任何查询。但是第二个查询有什么问题呢?

本机

PHP函数mysql_error可能会为您提供有关查询中可能的语法错误(以及其他类型的问题
(的宝贵提示http://php.net/manual/fr/function.mysql-error.php

此外,请考虑使用 mysqli 或 pdo_mysql,因为较旧的 mysql 扩展已从 PHP 5.5.0 开始被弃用。

在第二个查询中,也许您想使用像 sprintf 这样的字符串替换函数?

$query = sprintf("INSERT INTO allComments (IdPhoto,IdUser,comment,dates) VALUES ('%s',1,'%s','%s')", $photoId, $text, $date);
$result = mysql_query($query);