FOUND_ROWS() keeps returning 0

风格不统一 提交于 2020-01-11 03:40:13

问题


$result = $db_con->query("SELECT SQL_CALC_FOUND_ROWS * FROM users LIMIT 0,10");

$count_result = $db_con->query("SELECT FOUND_ROWS() as totalcount");
$row = $count_result->fetch_assoc();
$total = $row['totalcount'];

$total keeps returning 0 even though the $result contains all the user rows in it.

ini_set("mysql.trace_mode", "0");

I found out about this setting via searching a similar Q on here, but it did not resolve my issue.

When I use the 2 select statements in my MySQL client it always outputs the right count. Just can't seem to figure out how to get it working on my php page.

PHP Version: 5.2.5 build 6 MySQL Version: 5.1.30

Note: The code I provided here is not being used on my actual project, however, it does exemplify the problem I am having with not being able to retrieve the total count. This code, from what I've read about found_rows(), should work but it doesn't.


回答1:


On php.net I found someone with maybe the same problem. He is speaking of a race condition that could occur: php.net. Basically he solves this problem by temporary locking the table at the cost of slowing things down.




回答2:


LIMIT is required to make found_rows() work correctly

Add a LIMIT to the end of your query, ie.

SELECT SQL_CALC_FOUND_ROWS * FROM users LIMIT 0,10;

http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_found-rows

FOUND_ROWS() -- For a SELECT with a LIMIT clause, the number of rows that would be returned were there no LIMIT clause




回答3:


I'm not sure what database library you're using but it looks like you are trying to count the number of rows in a select statement in php from a mysql database.

Have you tried seeing if it works with the built in mysql database functions in php?

$count_result = mysql_query("SELECT COUNT(*) as totalcount FROM users");
$row = mysql_fetch_array($count_result);

$total = $row['totalcount'];


来源:https://stackoverflow.com/questions/1020745/found-rows-keeps-returning-0

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!