2015-08-23 24 views
-1

我一直試圖顯示我的數據庫的行數,但它顯示0行而不是8行。顯示來自db的行數與pdo

這裏是我的代碼:

$db_hostname="127.0.0.1"; 
    $db_name="..."; 
    $db_username="..."; 
    $db_password=""; 

    try { 
       $pdo=new PDO("mysql:host=$db_hostname;db=$db_name", $db_username, $db_password); 


        echo "Connection established"; 


      } catch (PDOException $e) { 
       echo 'Cannot connect to database'; 
       exit; 

      } 

PHP代碼:

<?php include_once 'connection.inc.php'; 

try { 

$sql='SELECT count(*) FROM images'; 

$result = $pdo->prepare($sql); 

$result->execute(); 

$count= $result->rowCount(); 

echo $count; 

$result->closeCursor(); 


catch (PDOException $e) { 

echo "Error in code".$e->getMessage(); 
} 
?> 

回答

3

您應該使用fetch*函數來獲取查詢結果:

$result = $pdo->prepare($sql); 
$result->execute(); 
$row = $result->fetch(); 
print_r($row); // and see what key do you need in it 
3

你的結果集應包含一行。該行包含一列,該列又包含您的images表中的行數。所以,與其

$count = $result->rowCount(); 

它檢索的行數在你的結果集,你想

$row = $result->fetch(PDO::FETCH_NUM); 
$count = $row[0]; 
0

你可以在你的SQL語句

$sth = $conn -> prepare("select count(*) as num_items from items"); 
$sth -> execute(); 
$result = $sth -> fetch(PDO::FETCH_ASSOC); 

echo $result['num_items']; //will output num of rows in the table if the table has records 
+0

'numrows'會給查詢返回的行數。 'count(*)'計算行數並將計數返回爲一行。所以這隻會返回'1'。這個查詢的值是OP所需要的。 – chris85

+0

@ Chris85檢查我的更新答案,我確實包含了完整的代碼。測試和它的作品。 – mdamia