使用以下PHP函数时遇到问题:
function saveCommentOnDB($arg_textComment, $arg_score, $arg_userEmail)
{
$result_tmp = null;
$this->conn->autocommit(false);
echo "saving\n";
echo "text comment: \n";
var_dump($arg_textComment); // OKAY
echo "comment score: \n";
var_dump($arg_score); // OKAY
echo "user mail: \n";
var_dump($arg_userEmail); // OKAY
try {
//[tag1] $query_1 = "INSERT INTO commenti (userFirstname, userEmail, textComment, score, feedback) VALUES ( (SELECT firstname FROM utente u WHERE u.userEmail = 'asd@asd.asd') ,'asd@asd.asd', 'This is an example comment.', 5, 0);";
$query_1 = "INSERT INTO commenti (userFirstname, userEmail, textComment, score, feedback) VALUES ( (SELECT firstname FROM utente u WHERE u.userEmail = ?) ,?,?, ?, 0);";
$query_2 = "UPDATE utente SET commentID=(SELECT c.commentID FROM commenti c WHERE c.userEmail = ?) WHERE userEmail = ?;";
$query_3 = "SELECT commentID, textComment FROM commenti WHERE userEmail = ?;";
$stmt1 = $this->conn->prepare($query_1);
$stmt2 = $this->conn->prepare($query_2);
$stmt3 = $this->conn->prepare($query_3);
$stmt1->bind_param("sssd", $arg_userEmail, $arg_userEmail, $arg_textComment, $arg_score);
$stmt2->bind_param("ss", $arg_userEmail, $arg_userEmail);
$stmt3->bind_param("s", $arg_userEmail);
$stmt1->execute();
$stmt2->execute();
$stmt3->execute();
$stmt3->bind_result($col1, $col2);
$stmt3->fetch();
echo "result:\n";
var_dump($col1); // OKAY
var_dump($col2); // OKAY
$result_tmp = array(
'commentID' => $col1,
'textComment' => $col2
);
$this->conn->commit();
} catch (Exception $e) {
$this->conn->rollback();
}
return $result_tmp;
}
请忽略echo
和var_dump
,我将它们仅用于调试。
问题是在这个函数中这三个准备好的语句似乎工作不正确。特别是声明$stmt1
:$stmt3
的结果是正确的(好像$stmt1
和$stmt2
正确执行了),但我看不到任何内容数据库。换句话说:这些陈述可以正常地“暂时”发挥作用。在执行期间,但在MyPHP Admin中,表commenti
上没有任何内容。
例如,我们假设在DB上有这个:
现在我使用以下参数启动该功能:
$arg_textComment = 'This is an example comment'
$arg_score = '5'
$arg_userEmail = 'asd@asd.asd'
我们在浏览器控制台上:
ie:commentID(28)是正确的,评论文本( commentcomment )是"已保存",然后我重新检查数据库,但我还是这样:
执行后和var_dump($stmt1)
为:
stmt1:
object(mysqli_stmt)#4 (10) {
["affected_rows"]=>
int(1)
["insert_id"]=>
int(41)
["num_rows"]=>
int(0)
["param_count"]=>
int(4)
["field_count"]=>
int(0)
["errno"]=>
int(0)
["error"]=>
string(0) ""
["error_list"]=>
array(0) {
}
["sqlstate"]=>
string(5) "00000"
["id"]=>
int(4)
}
var_dump
似乎没问题,但是DB nope。
所以我尝试手动执行查询'通过这个(它只会将代码执行到绿色框中):
我有我的期望:
sql> INSERT INTO commenti (userFirstname, userEmail, textComment, score, feedback) VALUES ( (SELECT firstname FROM utente u WHERE u.userEmail = 'asd@asd.asd') ,'asd@asd.asd', 'commentcomment', '5', 0) [2017-01-21 17:38:28] 1 row affected in 11ms
请注意,score
值会作为float
存储在数据库中。
$stmt1
的SQL查询与我通过PHPStorm手动插入的INSERT INTO...
相同。
为什么第一个不起作用而第二个是?
希望这个截屏视频可以提供帮助:
答案 0 :(得分:0)
问题解决了,改变了:
$stmt1->execute();
$stmt2->execute();
$stmt3->execute();
到此:
$stmt1->execute();
$this->conn->commit();
$stmt2->execute();
$this->conn->commit();
$stmt3->execute();
$this->conn->commit();
不知道为什么......但经过多次测试后才有效。