Web Hosting Talk







View Full Version : Need a little help with a php/mysql error.


Abaddon
04-18-2010, 02:48 PM
Im still kinda new to php and im getting the following error in a script.

Warning: Wrong parameter count for max()

The code im using is as follows.


$query = mysql_query("SELECT COUNT(`id`) as hits FROM `responses` GROUP BY `qid`");
while($row = mysql_fetch_array($query)){
$me[] = $row['hits'];
}
$max = max($me);


Whats weird is the script works perfect, except that error code keeps displying.

Im pretty sure that its just doing it because the actual amount of 'hits' is zero at the moment. How would I be able to fix it to where it does not show that error if nothing is returned from the database?

fabin
04-18-2010, 05:28 PM
Change it to

$max = @max($me);

mattle
04-19-2010, 08:35 AM
How do you suppose that hiding the error will solve the problem? I don't see immediately why this code would be failing, but you should start by examining the contents of $me. Put a var_dump($me) before your max() call and post the results.

fabin
04-19-2010, 09:10 AM
have you initialized the array?

$me = array()

mattle
04-19-2010, 10:37 AM
That's a decent point. Although it's perfectly legitimate to declare arrays on the fly in PHP, if the query returns no rows, the loop never executes and $me is never set. However, I get a different error message when this is the case (v5.3.0):


echo max(NULL);
echo max($bogus);


Both yield:

Warning: max(): When only one parameter is given, it must be an array...


Again, a var_dump() will be the most revealing debugging tool.

sbink
04-22-2010, 03:04 AM
How would I be able to fix it to where it does not show that error if nothing is returned from the database?

Simple: check to see if anything was returned from the database.


// assign max a default value
$max=0;
$query = mysql_query("SELECT COUNT(`id`) as hits FROM `responses` GROUP BY `qid`");
if (mysql_num_rows($query)) {
// as mentioned, always a good idea to initialize your variables
$me=array();
while($row = mysql_fetch_array($query)){
$me[] = $row['hits'];
}
$max = max($me);
}

mattle
04-22-2010, 01:56 PM
While I don't have anything against what you wrote there, that's not all technically necessary.

Assuming that you can't have negative hits:


$me = array(0);
$query = mysql_query(...);
while ($row = mysql_fetch_array($query)) $me[] = $row['hits'];
$max = max($me);


Of course, there's more efficient ways to do this as well, probably the best being to start with your query:


SELECT COUNT(id) hits FROM responses GROUP BY qid ORDER BY hits DESC LIMIT 1