0
votes

I have the loop over mysql data rows in php and I want to compare value from one row to the value from the next row. I so far did a code like this:

if ($result->num_rows > 0) {
     // output data of each row
     while($row = $result->fetch_assoc()) {
        $current_row = $row;
        $next_row = $row+1;
        if ($current_row["begin_date"] > $next_row["end_date"])
        {
           (...)
        }
     }
} else {
     echo "0 results";
}

but I get an error saying that $row+1 produces Fatal error: Unsupported operand types. How can I fix it?

For example, when I have rows like this:

     begin_dates | end_dates
row1:    value1  |  value2
row2:    value3  |  value4
row3:    value5  |  value6
row4:    value7  |  value8

and I want to compare value2 with value3, value4 with value5 and value6 with value7 - how can I do it in the loop? Also - does php handle sth like indexarrayoutofbounds exception? I want to make this loop generic and don't worry in the future to reach the last index, for example in that case since value8 is the last one - I don't want to compare it with null value (not existing value9). Thanks!

1
I think you should first save all the rows in an array and the sort the array.. - habib ul haq
could you give me a hint how to do it? and the other question is - what about the performance? is it faster to save all data to array and sort the array or sort it while performing the sql query (order by...) ? - randomuser2
How would $row+1 get the next row ? - adeneo

1 Answers

2
votes

$row+1 doesn't get you the next row

if ($result->num_rows > 0) {

    $arr = array();

    while($row = $result->fetch_assoc()) {     
       $arr[] = $row;
    }

    for($i=0; $i < count($arr); $i++) {
        $current_row = $arr[$i];
        $next_row    = $arr[$i+1];

        if ($current_row["begin_date"] > $next_row["end_date"]) {
           (...)
        }
     }
} else {
     echo "0 results";
}