简体   繁体   English

如何显示SQL中count返回的值

[英]How to display the values returned by count in SQL

i keep having this error "mysql_fetch_array() expects parameter 1 to be resource, null given in" when i try to display the returned value of count in sql. 当我尝试在sql中显示count的返回值时我一直出现此错误“ mysql_fetch_array()期望参数1为资源,给定为null” heres my code. 这是我的代码。

$query="SELECT med_rec_ID, COUNT(med_rec_ID) 
        FROM med_issue 
        WHERE MONTH(issue_date) = MONTH('2013-02-05')
        GROUP BY med_rec_ID";
$result= mysql_query($query);
while($count = mysql_fetch_array($display3)){
    echo $count[0];
}

i have tried to run the query in sql alone it displays 2 columns (the med_rec_ID, and the COUNT). 我试图单独在sql中运行查询,它显示2列(med_rec_ID和COUNT)。 guys how do i display the count and fix the error too? 伙计们我该如何显示计数并修复错误?

First of all, don't use mysql_* functions since they're deprecated. 首先,不要使用mysql_*函数,因为它们已被弃用。 Use mysqli or PDO . 使用mysqliPDO

Secondly, look at what you're passing into the fetch_array function. 其次,查看传递给fetch_array函数的内容。

You probably want to do something like: 您可能想要执行以下操作:

$link = mysqli_connect("localhost", "admin", "pass", "db_name");
$result = mysqli_query($link, $sql);
while($row = $result->fetch_array(MYSQLI_ASSOC)){ 
$medIds[] = $row['med_rec_ID'];
... 
}

Then fix the count by giving it an alias. 然后通过给它一个别名来固定计数。

Please note that you should actually store how you access the DB in a more secure manner, but I use this only to illustrate the example. 请注意,您实际上应该以更安全的方式存储访问数据库的方式,但是我仅以此为例进行说明。 Here's a pretty good post: How to create global configuration file? 这是一篇不错的文章: 如何创建全局配置文件?

Give it an alias: 给它起一个别名:

SELECT 
  med_rec_ID, 
  COUNT(med_rec_ID) TheCount
FROM med_issue 
where MONTH(issue_date) =     MONTH('2013-02-05') GROUP BY med_rec_ID

then you can select that column TheCount inside the while loop with $row['TheCount'] , also use lope through the $result : 然后您可以在$row['TheCount'] loop $row['TheCount']的while循环中选择TheCount $row['TheCount'] ,也可以在$result使用lope:

$result = mysql_query($query);

while($row = mysql_fetch_array($result)){
    echo $row['TheCount'];
}

Is your query even executing? 您的查询是否还在执行? that error will happen if mysql_query doesnt return the resource, in case query fails 如果mysql_query不返回资源,则该错误将发生,以防查询失败

$query="SELECT med_rec_ID, COUNT(med_rec_ID) as C FROM med_issue where MONTH(issue_date) =     MONTH('2013-02-05') GROUP BY med_rec_ID";
$result= mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_assoc($result))
   {
    echo $row["C"];
   }

Note: Please do not use mysql_* functions anymore 注意:请不要再使用mysql_ *函数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM