您的第二個電話$cxn->prepare
正在返回false
或null
。換句話說,第二個查詢無法創建語句。如前所述一個評論,它可能是由於你使用的保留字(table
),語法錯誤,或者是因爲連接超時等
假設這是類似PDO
的,你需要檢查您對prepare
調用返回聲明:
<?php
$stmt = $cxn->prepare('SELECT value FROM table WHERE column = ?');
if (!$stmt) {
// do something to deal with the failure
// throw new \Exception('Could not create statement');
}
$stmt->bind_param("i", $number);
$stmt->execute();
$stmt->bind_result($result);
while($stmt->fetch()) {
$stmt = $cxn->prepare('SELECT value FROM table2 WHERE column = ?');
if (!$stmt) {
// failed, handle it
// throw new \Exception('Could not create statement');
}
$stmt->bind_param("i", $result); // error on this line
$stmt->execute();
$stmt->bind_result($result2);
$stmt->fetch();
}
或者你也可以設置PDO的錯誤模式出問題時拋出異常和catch
。
<?php
$cxn->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
// after the above, failing calls to $cnx->prepare will throw exceptions
如果是PDO,你可以使用PDO::errorInfo
和PDO::errorCode
追蹤您的問題:
<?php
$stmt = $cxn->prepare('SELECT value FROM table WHERE column = ?');
if (!$stmt) {
var_dump($cxn->errorInfo());
return;
}
errorInfo
會給你回來的SQLSTATE代碼爲第一要素,驅動程序特定的陣列錯誤代碼作爲第二個,而實際的錯誤消息作爲第三個。這是開始尋找您的查詢失敗原因的地方。如果您確實設置了連接以引發異常,exception itself將提供您需要的信息(PDOException::getMessage
,PDOException::$errorInfo
等)。
如果您使用的是實際代碼'SELECT value FROM table WHERE column =?','table'是一個保留的MySQL字http://dev.mysql.com/doc/refman/5.5/en/reserved- words.html,並需要在返回蜱裏面。另外如果你的值不是一個整數'i',那麼它會產生一個錯誤,如果這不是什麼被傳遞的值。如果它是一個字符串,那麼使用''' - 答案實際上在錯誤信息中。 –
不要循環查詢。 > _ <你可以在一個查詢中完成所有操作。更高效和更安全。 –
不,它們只是我放入的放置值。它們在我的實際代碼中不同。 – Burrows