php mysql计入PHP变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/797335/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 23:53:26  来源:igfitidea点击:

mysql count into PHP variable

phpmysqlcount

提问by Duncan Benoit

Let say that we have the following query:

假设我们有以下查询:

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

this query will return the number of the users from a table. I need to pass this value to a PHP variable. I'm using this:

此查询将从表中返回用户数。我需要将此值传递给 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;
}

please correct my code where you think is necessary.

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

Which is the best approach. How do you recommend to do this ?

这是最好的方法。你建议如何做到这一点?

回答by Greg

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

回答by millimoose

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

此外,使用 mysqli 的替代方法,无论如何您都应该使用它进行参数插值:

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