mysql_num_rows是否有效和/或标准做法? [英] Is mysql_num_rows efficient and/or standard practice?

查看:97
本文介绍了mysql_num_rows是否有效和/或标准做法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

前一段时间,我在SQLite上闲逛,试图移植我的一些站点以使用它而不是MySQL.我迷上了像PHP的mysql_num_rows()那样缺乏统计结果的功能.经过一番搜索后,我发现此邮件列表,据我所知,它表示SQLite没有该功能,因为它效率低下.它指出,编写需要知道返回多少行的代码是一种不好的形式.

A while ago I was poking around with SQLite, trying to port some of my sites to use it instead of MySQL. I got hung up on the lack of a function to count results, like PHP's mysql_num_rows(). After searching a little I discovered this mail list, which says (as I understand it) that SQLite doesn't have that functionality because it's inefficient. It states that it is bad form to write code that needs to know how many rows are returned.

我通常使用mysql_num_rows检查空返回结果.例如:

I generally use mysql_num_rows to check for empty return results. For example:

$query = "SELECT * FROM table WHERE thing = 'whatever'";
$results = mysql_query($query);

if (mysql_num_rows($results)) {
    while ($row = mysql_fetch_array($results)) {
        echo "<p>$row[whatever]</p>";
    }
} else {
    echo "<p>No results found</p>";
}

SQLite社区对mysql_num_rows()概念的强烈反感使我想知道,对于PHP中的常规MySQL,这种效率是否如此之高?

The vehement distaste for the concept of mysql_num_rows() in the SQLite community makes me wonder if it's that terribly efficient for regular MySQL in PHP.

除了mysql_num_rows()之外,还有没有更好,更受人们接受的方法来检查PHP中MySQL结果集的大小?

Is there a better, more accepted way for checking the size of a MySQL result set in PHP besides mysql_num_rows()?

我不只是使用mysql_num_rows来获取计数-我将使用COUNT查询.我正在用它来检查是否有任何结果,然后再输出所有内容.这对于显示搜索结果之类的功能很有用-并不总是保证会有结果.在SQLite世界中,我必须发送一个COUNT查询,检查是否存在某些内容,然后发送一个SELECT查询以获取所有内容.

I'm not just using mysql_num_rows to get the count--I would use a COUNT query for that. I'm using it to check if there are any results before outputting everything. This is useful for something like displaying search results - it's not always guaranteed that there will be results. In SQLite world, I have to send one COUNT query, check if there is something, and then send a SELECT query to get everything.

推荐答案

您已经有了可以告诉您mysql_fetch_array()结果的信息.如果没有更多行要获取,则返回false(从 php .net ).

You already have something that is telling you if you've got results in mysql_fetch_array(). It returns false if there are no more rows to fetch (from php.net).

$query = "SELECT * FROM table WHERE thing = 'whatever'";
$results = mysql_query($query);
if($results) {
    $row = mysql_fetch_array($results);
    if($row) {
        do {
            echo "<p>{$row[whatever]}</p>";
        } while($row = mysql_fetch_array($results));
    } else {
        echo "<p>No results found</p>";
    }

} else {
    echo "<p>There was an error executing this query.</p>";
}

这篇关于mysql_num_rows是否有效和/或标准做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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