Whats the best way to get total # of records in a mysql table with php?

后端 未结 10 522
后悔当初
后悔当初 2021-01-12 05:51

Whats the most efficient way of selecting total number of records from a large table? Currently, Im simply doing

$result = mysql_query(\"SELECT id FROM table         


        
相关标签:
10条回答
  • 2021-01-12 06:15

    Can I just add, that the most "efficient" way of getting the total number of records, particularly in a large table, is to save the total amount as a number in another table. That way, you don't have to query the entire table everytime you want to get the total.

    You will however, have to set up some code or Triggers in the database to increase or decrease that number when a row is added/deleted.

    So its not the easiest way, but if your website grows, you should definitely consider doing that.

    0 讨论(0)
  • 2021-01-12 06:17

    What about something like this:

    $result = mysql_query("SELECT COUNT(id) AS total_things from table");
    $row = mysql_fetch_array($result,MYSQL_ASSOC);
    $num_results = $row["total_things"];
    
    0 讨论(0)
  • 2021-01-12 06:19

    Even though I agree to use the built-in functions, I don't really see any performance difference between mysql_num_rows and count(id). For 25000 results, same performance (can say exact.) Just for the record.

    0 讨论(0)
  • 2021-01-12 06:21

    You should use SQL's built in COUNT function:

    $result = mysql_query("SELECT COUNT(id) FROM table");
    
    0 讨论(0)
提交回复
热议问题