mysql count into PHP variable

前端 未结 2 518
闹比i
闹比i 2020-12-03 09:02

Let say that we have the following query:

SELECT DISTINCT COUNT(`users_id`) FROM `users_table`;

this query will return the number of the us

相关标签:
2条回答
  • 2020-12-03 10:01

    Also, an alternative using mysqli, which you should be using anyway for parameter interpolation:

    $statement = $connection->prepare($the_query_from_above);
    $statement->execute();
    $statement->bind_result($nr_of_users);
    $statement->fetch();
    
    0 讨论(0)
  • 2020-12-03 10:03

    Like this:

    // Changed the query - there's no need for DISTINCT
    // and aliased the count as "num"
    $data = mysql_query('SELECT COUNT(`users_id`) AS num FROM `users_table`') or die(mysql_error());
    
    // A COUNT query will always return 1 row
    // (unless it fails, in which case we die above)
    // Use fetch_assoc for a nice associative array - much easier to use
    $row = mysql_fetch_assoc($data);
    
    // Get the number of uses from the array
    // 'num' is what we aliased the column as above
    $numUsers = $row['num'];
    
    0 讨论(0)
提交回复
热议问题