使用PDO的mysql_num_rows的替代方法 [英] Alternative for mysql_num_rows using PDO
本文介绍了使用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屋!
查看全文