简体   繁体   中英

PHP, MySQL Query Always Returning 1?

I know I have more than one result in the table, can anyone tell me what I am doing wrong?

<?php
$con = mysql_connect("x","y","z");
if (!$con)
{
die(mysql_error());
}
mysql_select_db("mydatabase", $con);
$query = ("SELECT COUNT(*) FROM usersonline WHERE datetime > NOW() - INTERVAL 5 MINUTE");
$result = mysql_query($query);
$num_rows = mysql_num_rows($result);
echo $num_rows;
?>

The result of mysql_num_rows will be one, you're only selecting one row from the database, it just happens to be the count of records that match a condition. Try this:

$query = ("SELECT COUNT(*) AS cnt FROM usersonline WHERE datetime > NOW() - INTERVAL 5 MINUTE");
$result = mysql_query($query);
$row = mysql_fetch_array($result);
$num_rows = $row['cnt'];
echo $num_rows;

You're using the aggregate COUNT() function without a GROUP BY clause. It'll collapse the entire result set down and count the number of records, so all you'll ever get back is a 1-row-with-1-field result set.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM