php 使用 PDO 的 mysql_num_rows 替代方案

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11305230/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 00:13:43  来源:igfitidea点击:

Alternative for mysql_num_rows using PDO

phpmysqlpdo

提问by user1323294

Right now I have a PHP file that does a MYSQL query and then counts rows like this:

现在我有一个 PHP 文件,它执行 MYSQL 查询,然后像这样计算行数:

$count=mysql_num_rows($result);


if ($count == 1) {
    $message = array('status' => 'ok');
} else {
    $message = array('status' => 'error');
}

This works fine but I'm trying to change all my PHP files to use PDO. So how can this be done with PDO?

这工作正常,但我正在尝试将所有 PHP 文件更改为使用 PDO。那么如何用 PDO 做到这一点呢?

采纳答案by WolvDev

$res = $DB->query('SELECT COUNT(*) FROM table');
$num_rows = $res->fetchColumn();

or

或者

$res = $DB->prepare('SELECT COUNT(*) FROM table');
$res->execute();
$num_rows = $res->fetchColumn();

You can use this to ask if data exists or is selected, too:

您也可以使用它来询问数据是否存在或被选中:

$res = $DB->query('SELECT COUNT(*) FROM table');
$data_exists = ($res->fetchColumn() > 0) ? true : false;

Or with your variables:

或者使用您的变量:

$res = $DB->query('SELECT COUNT(*) FROM table');
$message = ($res->fetchColumn() > 0) ? array('status' => 'ok') : array('status' => 'error');

回答by sekhar

$stmt = $db->query('SELECT * FROM table');  
$row_count = $stmt->rowCount();  
echo $row_count.' rows selected';

回答by priki

Maybe you can use PDO's "fetchAll" method, which returns an array containing all the SELECT results. Then use "count" method to count the array's rows.

也许您可以使用 PDO 的“fetchAll”方法,它返回一个包含所有 SELECT 结果的数组。然后使用“count”方法计算数组的行数。

Ex:

前任:

$rows = $stmt->fetchAll();
$num_rows = count($rows);

回答by shxfee

If you are not using prepared statements then try:

如果您没有使用准备好的语句,请尝试:

$find = $dbh->query('SELECT count(*) from table');
if ($find->fetchColumn() > 0){
    echo 'found';
}

However, if you choose prepared statements, which i highly recommend, then:

但是,如果您选择我强烈推荐的准备好的语句,那么:

$find = $dbh->prepare('SELECT count(*) from table');
$find->execute();
if ($find->fetchColumn() > 0){
    echo 'found';
}

回答by Jefferson Schiavetto

Can be like that...

可以这样...

$numRows = $conn->query("SELECT COUNT(*) FROM yourtable")->fetchColumn();
echo $numRows;