显示db with pdo的行数

时间:2015-08-23 20:32:29

标签: php mysql pdo

我一直在尝试显示数据库中的行数,但它显示0行而不是8行。

这是我的代码:

    $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 个答案:

答案 0 :(得分:3)

您应该使用fetch*函数来获取查询结果:

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

答案 1 :(得分:3)

您的结果集应包含一行。该行包含一列,该列又包含images表中的行数。所以,而不是

$count = $result->rowCount();

,它检索结果集中的行数,你想要

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

答案 2 :(得分: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