使用 PDO 的 mysql_num_rows 替代方案 [英] Alternative for mysql_num_rows using PDO

查看:29
本文介绍了使用 PDO 的 mysql_num_rows 替代方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

$count=mysql_num_rows($result);


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

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

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

推荐答案

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

$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;

或者使用您的变量:

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

这篇关于使用 PDO 的 mysql_num_rows 替代方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆