dongyue7796 2009-07-22 13:36
浏览 93
已采纳

mysql_num_rows是否有效和/或标准实践?

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.

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>";
}

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.

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

EDIT: 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.

  • 写回答

3条回答 默认 最新

  • douli8040 2009-07-22 13:47
    关注

    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>";
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题