简体   繁体   中英

Count MySQL rows

I run a minecraft server with an add-on called Log Block which logs all things done on the server, now I am making an "admin" panel there which dives into the database and will count the total number of blocks mined and placed.

But how shall I achieve this, I'm talking about 3 million rows and counting.

Should I make a cron job to run once a day with a count(*) and then save this result, or are there better ways to achieve this?

This is the code I have at this point

$result = mysql_query("SELECT count(id) FROM `lb-world` WHERE type='0' AND data='0'");
$result = mysql_fetch_array($result);
  $result = mysql_query("SELECT count(id) FROM `lb-world` WHERE type='0' AND data='0'");
  $result = mysql_fetch_array($result);

  echo $result[0]; //Output amount of rows
$result = mysql_query("SELECT id FROM `lb-world` WHERE type='0' AND data='0'");
$result = mysql_num_rows($result);
echo $result;

above code working fine. another example see below:

$result = mysql_query("SELECT count(id) AS myid FROM `lb-world` WHERE type='0' AND data='0'");
$result = mysql_fetch_array($result);
echo $result['myid'];

If you only want the count of the prior day, then run a cron at the start of the day to get the count. If you want more accurate counts, keep hourly or so stats. With large amounts, it might not be best to do a count every page load.

The thing you may wish to also do is use the MySQL AS statement to make your code a little clearer.

SELECT COUNT(id) AS count FROM...

This will return a column named count with the first row as the count. Then you can get the array ( *_fetch_array ) and get the value using:

$array['count']

This will return your desired count as mysql_num_rows will always return 1, since only one row was given.

NOTICE: do not use MySQL_* commands as they have been deprecated. Use MySQLi_* or PDO instead

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