Howto: Get Number of Rows

If you have a MySQL table and you want to know how many records there are in this table you can run a query on the entire table for example:

  1. <?php
  2.  
  3.   //setup a query to select all items
  4.   $query = mysql_query("SELECT * FROM `tablename`");
  5.  
  6.   //now use the magic row counter droid
  7.   $rows = mysql_num_rows($query);
  8.  
  9.   echo $rows;
  10. ?>

This will show you how many rows were supplied in that query. So if you want to find out how many people are under 18 in your forums you could do something like this:

  1. <?php
  2.  
  3.   $timegap = time() - (18 * 365 * 24 * 60 * 60);
  4.   $query = mysql_query("SELECT * FROM `tablename` WHERE `dob` < '".$timegap."'");
  5.   $rows = mysql_num_rows($query);
  6.   echo $rows;
  7. ?>

The time gap gets the time in seconds of 18 years, then subtracts it from the time now. Yay. so now you can limit access to minors :O

Post a Comment