mysql计数变成PHP变量 [英] mysql count into PHP variable

查看:87
本文介绍了mysql计数变成PHP变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有以下查询:

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

请更正我认为必要的代码。



这是最好的方法。



<$>

p $ p> //更改查询 - 不需要DISTINCT
//并将计数别名为num
$ data = mysql_query(' `)AS num FROM`users_table`')或die(mysql_error());

//一个COUNT查询将总是返回1行
//(除非失败,在这种情况下我们死在上面)
//使用fetch_assoc一个好的关联数组 - 更容易使用
$ row = mysql_fetch_assoc($ data);

//从数组中获取使用次数
//'num'是我们如上所述的列别名
$ numUsers = $ row ['num'];


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:

$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 ?

解决方案

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

这篇关于mysql计数变成PHP变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆