Php 使用pdo显示数据库中的行数
我一直试图显示数据库中的行数,但它显示的是0行,而不是8行 这是我的密码:Php 使用pdo显示数据库中的行数,php,mysql,pdo,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);
$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();
}
?>
您应该使用
fetch*
函数来获取查询结果:
$result = $pdo->prepare($sql);
$result->execute();
$row = $result->fetch();
print_r($row); // and see what key do you need in it
结果集应包含一行。该行包含一列,该列依次包含
images
表中的行数。因此,与其
$count = $result->rowCount();
它检索您想要的结果集中的行数
$row = $result->fetch(PDO::FETCH_NUM);
$count = $row[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
numrows
将给出查询返回的行数<代码>计数(*)计算行数并将计数作为一行返回。所以这只会返回1
。这个查询的值是OP需要的。@Chris85检查我的更新答案,我确实包含了完整的代码。经过测试,效果良好。