mysql计入PHP变量

时间:2009-04-28 11:04:46

标签: php mysql count

假设我们有以下查询:

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

此查询将返回表中的用户数。我需要将此值传递给PHP变量。我正在使用这个:

$sql_result = mysql_query($the_query_from_above) or die(mysql_error());

if($sql_result)
{
    $nr_of_users = mysql_fetch_array($sql_result);
}
else
{
    $nr_of_users = 0;
}

请在您认为必要的地方更正我的代码。

哪种方法最好。你怎么建议这样做?

2 个答案:

答案 0 :(得分:24)

像这样:

// 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'];

答案 1 :(得分:3)

另外,使用mysqli的替代方法,无论如何都要使用它进行参数插值:

$statement = $connection->prepare($the_query_from_above);
$statement->execute();
$statement->bind_result($nr_of_users);
$statement->fetch();