2012-06-26 73 views
0

如何從mysql查詢中選擇一行並將其保存到使用PDO的變量?以前我做了這樣的從mysql查詢中選擇行並將其保存到變量

$row = mysql_fetch_array($result); 

    $ID = $row['ID']; 

現在我從PHP手冊閱讀PDOStatement::fetch()是替代mysql_fetch_array,但我無法弄清楚如何使用它。這是我試過,但很明顯,如果你使用PDO::FETCH_OBJ它不工作

<?php 
include 'config.php'; 

$sql = "select * from table1"; 

try { 
    $dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass); 
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
    $stmt = $dbh->query($sql); 
    $result = $stmt->fetchAll(PDO::FETCH_OBJ); 
    $dbh = null; 
    echo '{"items":'. json_encode($result) .'}'; 
} catch(PDOException $e) { 
    echo '{"error":{"text":'. $e->getMessage() .'}}'; 
} 

$row = $stmt->fetchAll(PDO::FETCH_OBJ); 
    $ID = $row['ID']; 


?> 

回答

0

,你必須使用對象表示法來檢索結果的要素。由於您已經調用了fetchAll()方法,因此以後不能再調用另一個fetch/fetchAll方法,因爲數據將不再可訪問。

在地方的$row = $stmt->fetchAll(PDO::FETCH_OBJ);,遍歷$result變量,你以前有fetchAll()返回到:

foreach($result as $row) 
{ 
    $ID = $row->ID; 
    // Etc... 
} 
+0

當我嘗試回聲$ ID它給了我錯誤'未定義的變量:' – user1323294

+0

@ user1323294,擺脫在'try'塊中的'$ result = $ stmt-> fetchAll(PDO :: FETCH_OBJ);'行。原因是因爲在'fetchAll()'之後你將無法訪問數據。 –

+0

但如果我把'$ result = $ stmt-> fetchAll(PDO :: FETCH_OBJ);'它顯示爲'null'作爲'json_encode($ result)',對吧?你能否給我提供我的帖子中的代碼完整樣本。 – user1323294

相關問題