我有以下功能來準備和執行和返回結果。我稱之爲準備我的插入查詢並將值綁定到它並返回執行結果。但是當我檢查出功能範圍內受影響的行數時,它會得到-1,但是我的預期記錄已插入到我的表中。我們是否必須總是在全局中定義準備的語句變量?
function prepare_and_run($link,$query_structure){
$stmt = mysqli_prepare($link,$query_structure);
mysqli_stmt_bind_param($stmt, 's', 'a string value');
mysqli_stmt_execute($stmt);
$result=mysqli_stmt_get_result($stmt);
if($result===false && !mysqli_errno($link))
return true;
return $result;
}
//call the function above
$link=mysqli_connect(...);
$result=prepare_and_run($link,"insert into table values(?)");
echo mysqli_affected_rows($link); // output: -1 !!!
我加3行代碼和看到它是固定的:
$dpq_stmt=null; // it is added
function prepare_and_run($link,$query_structure){
$stmt = mysqli_prepare($link,$query_structure);
mysqli_stmt_bind_param($stmt, 's', 'a string value');
mysqli_stmt_execute($stmt);
global $dpq_stmt; // it is added
$dpq_stmt=$stmt; // it is added
$result=mysqli_stmt_get_result($stmt);
if($result===false && !mysqli_errno($link))
return true;
return $result;
}
//call the function above
$link=mysqli_connect(...);
$result=prepare_and_run($link,"insert into ...");
echo mysqli_affected_rows($link); // output: 1 . it is correct
但爲什麼呢?我們是否必須總是在全局中定義準備好的語句變量?