Cadz
Cadz

Reputation: 151

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. 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). guys how do i display the count and fix the error too?

Upvotes: 1

Views: 563

Answers (3)

Eric Hotinger
Eric Hotinger

Reputation: 9306

First of all, don't use mysql_* functions since they're deprecated. Use mysqli or PDO.

Secondly, look at what you're passing into the fetch_array function.

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?

Upvotes: 1

Mahmoud Gamal
Mahmoud Gamal

Reputation: 79919

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:

$result = mysql_query($query);

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

Upvotes: 0

Hanky Panky
Hanky Panky

Reputation: 46900

Is your query even executing? that error will happen if mysql_query doesnt return the resource, in case query fails

$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

Upvotes: 0

Related Questions