我正在開發一個旨在使用 PDO 查詢資料庫的函式。我正在使用要執行的陣列。我收到錯誤 HY093。下面是我的代碼
//my function
function test_function($statement,$data,$connect)
{
$gg = implode(',',$data);
$sth = $connect->prepare($statement);
$sth ->execute(array($gg));
$r_result = $sth->fetch();
$show_result = $r_result['0'];
return $show_result;
}
$datas = array("':ids' => 1"," ':stats' => 1");
$showsh = test_function("SELECT COUNT(*) FROM table WHERE col1 > :ids AND col2 =
:stats",$datas,$con);
echo $showsh;
任何指導都會有所幫助。
uj5u.com熱心網友回復:
您的第一個錯誤是創建陣列。您正在創建一個包含 2 個字串的陣列,而不是一個包含 2 個鍵/值對的陣列。應該是這樣的:
$datas = array(':ids' => 1,':stats' => 1);
接下來是函式內部。您正在將$data變數轉換為字串,然后將其傳遞給陣列內部的查詢。忘記這一切,然后$data進入你的執行。
$sth = $connect->prepare($statement);
$sth ->execute($data);
uj5u.com熱心網友回復:
重構$datas為[":ids" => 1, ":stats" => 1]
然后編輯函式:
function test_function($statement,$data,$connect)
{
$sth = $connect->prepare($statement);
$sth ->execute($data);
$r_result = $sth->fetch();
$show_result = $r_result['0'];
return $show_result;
}
如果您不能更改$datas格式,則必須在代碼中對其進行重構。就像是:
$correctData = [];
foreach ($datas as $item) {
$elements = explode("=>", $item);
$key = preg_replace("/\s\'/", "", $elements[0]);
$element = preg_replace("/\s\'/", "", $elements[1]);
$correctData[] = [$key => $element];
}
$showsh = test_function("SELECT COUNT(*) FROM table WHERE col1 > :ids AND col2 =
:stats",$correctData,$con);
編輯: preg_replace("(/\s)(\')/", "",...到preg_replace("/\s\'/", "",...
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/460609.html
上一篇:僅使用一個查詢替換兩個字串/資料
下一篇:SQL查詢未產生預期結果
