Max value in a while loop?

I have a simple prepared statement query with news items which I order by date DESC

Then I use a while loop to output the news items:


while($row = $news->fetch()) {
    echo "<h1>{$row['news_title']} - {$row['news_date']}</h1>";
    echo "<p>{$row['news_content']}</p>";
}

What I need within the while loop is the highest news_id which I need for an update that also needs to take place within that loop.

I have tried the max function:


$last_id = MAX($row['news_id']);	

But get the following error:

Cannot use object of type stdClass as array

and on:

$last_id = MAX($row->bericht_id);

i get

Trying to get property of non-object in

How should I use the MAX function in this case to get the last_id?

Thank you in advance!

The problem seems to be that max() is expecting more than one parameter - if you think about it, you’re asking for the max of one value. So maybe it would be


$last_id = MAX($row['news_id'], $last_id);

or


$last_id = MAX($row->bericht_id, $last_id);

Hi droopsnoot. Thanks a lot for the reaction. I tried both of your options but unfortunately both are giving me errors.

The first: Undefined index: news_id

and the second: Trying to get property of non-object

The problem is you’re trying to use a one at a time operation as a global operation. fetch() returns one row at a time, so you can’t parse out looking for a maximum value for one row.

Way I see it, you have two choices:

  1. Run two db queries using the same criteria for both, one looking for a max value, and one returning the full recordset
    [LIST=1]
  2. advantage - less php processing
  3. disadvantage - second trip to the database
    [/LIST]
  4. Place the result set into an associative array (using fetchAll() for example), then loop through the array twice, once to find max value of column, once to display
    [LIST=1]
  5. advantage - single trip to the database, no chance of difference in result set.
  6. disadvantage - depending on size of returned array, multiple loops through the arrays can be expensive and slow.
    [/LIST]

note: For option two, you can use usort as well, but you’ll want to do that with a different array as it reorders the entire array and that may be a different order than you actually want - may also be expensive depending on size of result set as well.

Do you have a column called “news_id” in your table, and are you retrieving it in your query? If not, that would cause it. I can’t see that bit of code.

Hi Dave. Thank you so much for the reply. I think my preference would be example 2. The only problem is, how do I loop over the array just twice? I realy have no idea how that should look like?

Thank you in advance

There is another option: you can keep track of the news_id value as you loop over the records. That way you only loop the records once.


$news_id = 0;

while($row = $news->fetch()) {
    if ($row['news_id'] > $news_id) {
        $news_id = $row['news_id'];
    }
    echo "<h1>{$row['news_title']} - {$row['news_date']}</h1>";
    echo "<p>{$row['news_content']}</p>";
}

// $news_id is now set to the highest news_id value

I would agree with you except he included this caveat (emphasis mine):

So I’m assuming he’s going to want to highlight the highest news_id

Something like this (sorry for any syntax errors, my php is a little rusty):


$news_id = 0; 
$result_set = $news->fetchAll();  // retrieves all the rows for a resultset and places it into an array

// loop through to get the highest
foreach ($row in $result_set) {
    if ($row['news_id'] > $news_id) {
        $news_id = $row['news_id']; 
    }
}

// now loop through for display
foreach ($row in $result_set) {
    $class = ($row['news_id'] == $news_id) ? " class=\\"highlight\\"" : "")            // assigns value to a string value if the news_id is the greatest found in prev loop
    echo "<h2{$class}>{$row['news_title']} - {$row['news_date']}</h2>";  
    echo "<p>{$row['news_content']}</p>";  
}

Hi David & fretburner. Thank you both for the reply and input

I don’t need to highlight the highest news_id, I need it for an update within the loop for display. So does that mean that I can use fretburner’s example?

I’m really confused. What do you mean you need it for an update within the loop for display? Are you looping through the list, and in one of those list items you want to show it’s the highest? Or are you doing something like a summary where you’ve shown all the data THEN display an indicator of which is the highest?

If it’s IN the list, you’ll have to use mine. If you’re doing something in summary, then you can use fretburners.

The loop for display shows all news items (incl the last one) from a certain writer/editor in DESC order. The most recent news item has status isNew = 1. I need to use the update query in the while loop to set the status isNew for the most recent message to 0. I use Long Polling to keep the listing as up to date as possible so when I don’t set the isNew status to 0 the list with news items will keep repeating itself.

Still not sure I completely understand, but why not just include isNew in your query, and when the value is 1, use the news_id to run your update?

Hi Dave. I think you understand it better than you give yourself credits for :slight_smile:

This is without doubt the simplest yet most efficient solution one could come up with. I kept focussing on the most recent news_id, but since all the news items in the loop are from the same writer that was/is not necessary at all.

Thank you so much :tup:

I’m very good at simple :smiley:

Glad we were able to help you figure out a solution…