Page 1 of 1

Newbie needs help using MAX function

Posted: Sun Jul 08, 2007 5:41 pm
by slade27
I'm a newbie having trouble understanding the proper use of the MAX function. I've seen a lot of examples online, which I've tried to apply in my case, but so far no luck. Could someone please look at the latest incorrect ways that I've tried to use the function below and tell me where I'm going wrong?

Thanks.

My first attempt:

In the following test example that I've been working with, I'm trying to calculate the maximum value of a numeric INT field called count in a table called Britishism:

Code: Select all

$sql="SELECT MAX(count) as $maxcount FROM Britishism";

$result2 = mysql_query($sql);

echo "Highest count is ".$result2;
I'm using $result2 above instead of $result because this portion of the script is actually nested inside the following WHILE function that has already used a variable called $result:

while ($row = mysql_fetch_assoc($result)) {
}

My second attempt:

I also tried something like the following, without using MAX directly in a SELECT statement, but instead, calling the function during the execution of a WHILE statement, as in:

Code: Select all

while ($row = mysql_fetch_assoc($result)) {

$maxcount = MAX($row['count']);

echo "Highest value in count field is ".$maxcount;
}

...but that didn't work either.

Posted: Sun Jul 08, 2007 6:24 pm
by volka
In your first attempt there is no call to mysql_fetch_[assoc|row|array] or mysql_result.

Code: Select all

<?php
error_reporting(E_ALL);
ini_set('display_errors', true);
ini_set('mysql.trace_mode', true);

$sql="SELECT MAX(count) as $maxcount FROM Britishism";
$result2 = mysql_query($sql) or die(mysql_error().': '.$sql);
echo 'Highest count is ', mysql_result($result2, 0);
...but that didn't work either.
"doesn't work." usually isn't a very helpful statement.
If you get an error/warning/notice message please post it.
If you do not get a message let the script start with

Code: Select all

error_reporting(E_ALL);
ini_set('display_errors', true);
ini_set('mysql.trace_mode', true);

Posted: Sun Jul 08, 2007 6:41 pm
by superdezign
In order to use MAX(), you must specify which property to group the results by with GROUP BY.

Though, I could have sworn I've done it without it before...

Edit: Yeah, you can. There's something else. Check mysql_error().