my sql best practice with php for counting rows

前端 未结 4 891
情书的邮戳
情书的邮戳 2021-01-28 18:31

1) Count record:

//Connect to mysql server
$link = mysql_connect(HOST, USER, PASSWORD);
if(!$link) {
    die(\'Could not connect to server: \' . mysql_error());
         


        
相关标签:
4条回答
  • 2021-01-28 19:01

    When you only need the count the record, you should use COUNT() function of mysql, instead of load all of the records.

    $query="SELECT COUNT(*) AS num FROM `table` WHERE `abc`='123'";
    

    Second, use PDO instead of mysql_ functions.

    0 讨论(0)
  • 2021-01-28 19:16
    $query="SELECT COUNT(id) FROM `table` WHERE `abc`='123'";
    $result = mysql_query($query);
    $count = mysql_fetch_row($result);
    

    This will work fast and light. Also, as Jack said in the comments above, you should use either MySQLi, or PDO, because the MySQL addon has been deprecated by PHP.

    0 讨论(0)
  • 2021-01-28 19:17

    Why not the let the DB do it - What about a simple

    SELECT COUNT(*) FROM table WHERE abc=123;
    
    0 讨论(0)
  • 2021-01-28 19:25

    mysql has a count function:

    http://dev.mysql.com/doc/refman/5.1/en/counting-rows.html

    so you could use:

    SELECT COUNT(*) FROM table WHERE abc=123
    

    or whatever condition.

    0 讨论(0)
提交回复
热议问题