gpt4 book ai didi

php - mysql 计数到 PHP 变量

转载 作者:可可西里 更新时间:2023-11-01 06:53:05 25 4
gpt4 key购买 nike

假设我们有以下查询:

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;
}

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

哪种方法最好。您建议如何执行此操作?

最佳答案

像这样:

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

关于php - mysql 计数到 PHP 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/797335/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com