2013-10-27 31 views
0

我有以下代碼:查詢中使用以前查詢的結果

$stmt = $cxn->prepare('SELECT value FROM table WHERE column = ?'); 
$stmt->bind_param("i", $number); 
$stmt->execute(); 
$stmt->bind_result($result); 

while($stmt->fetch()) { 
    $stmt = $cxn->prepare('SELECT value FROM table2 WHERE column = ?'); 
    $stmt->bind_param("i", $result); // error on this line 
    $stmt->execute(); 
    $stmt->bind_result($result2); 
    $stmt->fetch(); 
} 

我想在第二個查詢使用結果從第一個查詢,但是,我得到線$stmt->bind_param("i", $result);以下錯誤:

Fatal error: Call to a member function bind_param() on a non-object 

怎麼了?

+1

如果您使用的是實際代碼'SELECT value FROM table WHERE column =?','table'是一個保留的MySQL字http://dev.mysql.com/doc/refman/5.5/en/reserved- words.html,並需要在返回蜱裏面。另外如果你的值不是一個整數'i',那麼它會產生一個錯誤,如果這不是什麼被傳遞的值。如果它是一個字符串,那麼使用''' - 答案實際上在錯誤信息中。 –

+2

不要循環查詢。 > _ <你可以在一個查詢中完成所有操作。更高效和更安全。 –

+0

不,它們只是我放入的放置值。它們在我的實際代碼中不同。 – Burrows

回答

0

您的第二個電話$cxn->prepare正在返回falsenull。換句話說,第二個查詢無法創建語句。如前所述一個評論,它可能是由於你使用的保留字(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::errorInfoPDO::errorCode追蹤您的問題:

<?php 
$stmt = $cxn->prepare('SELECT value FROM table WHERE column = ?'); 
if (!$stmt) { 
    var_dump($cxn->errorInfo()); 
    return; 
} 

errorInfo會給你回來的SQLSTATE代碼爲第一要素,驅動程序特定的陣列錯誤代碼作爲第二個,而實際的錯誤消息作爲第三個。這是開始尋找您的查詢失敗原因的地方。如果您確實設置了連接以引發異常,exception itself將提供您需要的信息(PDOException::getMessagePDOException::$errorInfo等)。

+0

是的,它返回false,但我不知道爲什麼。 – Burrows

+0

查看我的編輯:如果是PDO,可以使用'errorInfo'開始追蹤。 – chrisguitarguy

+0

所以事實證明,我必須在第一次查詢後添加'$ stmt-> close();',但我不知道爲什麼。你可以解釋嗎? – Burrows