php 使用 mysql_fetch_array 我可以轻松计算返回的行数。我可以用 mysql_fetch_object 做类似的事情吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4588135/
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
With mysql_fetch_array I can easily count the rows returned. Can I do something similar with mysql_fetch_object?
提问by David Rhoden
(Apologies if necessary--my first Stack Overflow question. I'll be happy to modify it if anyone has suggestions. I have looked for an answer but I'm afraid my grasp of the terminology isn't good enough to make a complete search.)
(如有必要,请道歉——我的第一个 Stack Overflow 问题。如果有人有建议,我很乐意修改它。我已经寻找了答案,但恐怕我对术语的掌握不够好,无法做出完整的搜索。)
I'm accustomed to using mysql_fetch_array to get records from a database. When getting records that way, mysql_num_rows gives me a count of the rows. On my current project, however, I'm using mysql_fetch_object. mysql_num_rows doesn't seem to work with this function, and when I do a 'count' on the results of the query I get the expected answer: 1 (one object).
我习惯使用 mysql_fetch_array 从数据库中获取记录。以这种方式获取记录时,mysql_num_rows 会给我一个行数。但是,在我当前的项目中,我使用的是 mysql_fetch_object。mysql_num_rows 似乎不适用于此函数,当我对查询结果进行“计数”时,我得到预期的答案:1(一个对象)。
Is there a way to 'see into' the object and count the elements inside it?
有没有办法“查看”对象并计算其中的元素?
回答by ehudokai
The function mysql_num_rows
works on your result resource, not your object row.
该函数mysql_num_rows
适用于您的结果资源,而不是您的对象行。
Example
例子
$link = mysql_connect("localhost", "mysql_user", "mysql_password");
mysql_select_db("database", $link);
$sql = "SELECT id, name FROM myTable";
$result = mysql_query($sql, $link);
$rowCount = mysql_num_rows($result);
while($row = mysql_fetch_object){
echo "id: ".$row->id." name: ".$row->name."<BR>";
}
echo "total: ".$rowCount;
回答by simshaun
Try count( (array)$object )
.
试试count( (array)$object )
。
回答by Mitch Grande
If you're using it in procedural style (i.e. mysql_fetch_object() vs. $result->fetch_object()), mysql_num_rows should work exactly the same way as when using mysql_fetch_array(). Could you post some sample code?
如果您以程序风格使用它(即 mysql_fetch_object() 与 $result->fetch_object()),mysql_num_rows 的工作方式应该与使用 mysql_fetch_array() 时完全相同。你能发布一些示例代码吗?
回答by ElSqueleto
<?php
mysql_connect("localhost", "user", "password");
mysql_select_db("database");
$result = mysql_query("SELECT SQL_CALC_FOUND_ROWS * FROM table");
$countQuery = mysql_query("SELECT found_rows() AS totalRows");
$rows = mysql_fetch_object($countQuery);
echo $rows->totalRows;
?>
I hope this is useful :)
我希望这是有用的:)