问题:
无法使用mysqli_begin_transaction
将mySQL存储过程存储数据。
详细信息:
下面的代码将使用mysql存储过程执行简单的insert
和select
。代码运行良好没有 select
语句。但是,一旦添加了select
语句,即使查询在PHP端返回成功,它也不会提交任何数据。
代码段(PHP):
$DB_DRRM_SQLI = mysqli_connect("localhost","root","", "sandbox_db");
mysqli_begin_transaction($DB_DRRM_SQLI);
$SQL_QUERY_CODE = "CALL SANDBOX_TEST()";
$DB_QUERY = mysqli_query($DB_DRRM_SQLI, $SQL_QUERY_CODE);
// ERROR REPORTING
if($DB_QUERY === false)
{
echo mysqli_error($DB_DRRM_SQLI);
mysqli_rollback($DB_DRRM_SQLI);
}
else
{
echo 'success';
mysqli_commit($DB_DRRM_SQLI);
}
exit;
代码段(mySQL存储过程):
BEGIN
INSERT INTO
`sandbox_table`
(
`SOME_STRING`
)
VALUES
(
'ABCDEFGHIJKL...'
);
SELECT
LAST_INSERT_ID() AS INSERTED_ID,
'ABCDE...' AS OTHER_PARAMS;
END
数据库(表sandbox_table):
规格:
备注:
测试的方法:
sandbox_table
及以上存储过程外没有其他数据。答案 0 :(得分:0)
<强>解决方案:强>
这是由mysqli_commit
处的命令不同步错误引起的。似乎 mysqli 在查询打开时不允许提交事务,如果将select
语句添加到上述存储过程,则会发生这种情况。
因此,要处理此问题,必须先关闭查询或将查询置于缓冲区。
代码段(PHP):
// SQL Database
$DB_DRRM_SQLI = mysqli_connect("localhost","root","", "sandbox_db");
mysqli_begin_transaction($DB_DRRM_SQLI);
$SQL_QUERY_CODE = "CALL SANDBOX_TEST()";
$DB_QUERY = mysqli_query($DB_DRRM_SQLI, $SQL_QUERY_CODE);
// ERROR REPORTING
if($DB_QUERY === false)
{
echo mysqli_error($DB_DRRM_SQLI);
mysqli_rollback($DB_DRRM_SQLI);
}
else
{
// Must free current query result before committing transaction
@mysqli_free_result($DB_QUERY);
@mysqli_next_result($DB_DRRM_SQLI);
if(mysqli_commit($DB_DRRM_SQLI) === false)
{
echo mysqli_error($DB_DRRM_SQLI);
}
else
{
echo 'success';
}
}
exit;