Newbie needs help using MAX function

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
slade27
Forum Newbie
Posts: 21
Joined: Tue Apr 24, 2007 3:49 am

Newbie needs help using MAX function

Post 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.
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post 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);
User avatar
superdezign
DevNet Master
Posts: 4135
Joined: Sat Jan 20, 2007 11:06 pm

Post 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().
Post Reply