2

I'm trying to get the Min and Max value from an Mysql array. But I always get the same value as output.

    $query1 = "SELECT * FROM  `seriennummern` WHERE id = '$i'";
    $result1 = $mysqli->query($query1);
    $countSN = $result1->num_rows;
    while($row = $result1->fetch_array())
    {
        $max = (max(array($row['Seriennummer'])));
        $min = (min(array($row['Seriennummer'])));
        print_r(array($row['Seriennummer']));

    }

The output from print_r is

Array ( [0] => 53928 ) Array ( [0] => 56945 ) Array ( [0] => 58055 ) Array ( [0] => 59149 ) Array ( [0] => 70518 ) Array ( [0] => 72020 ) Array ( [0] => 71198 ) Array ( [0] => 51161 ) Array ( [0] => 56945 ) Array ( [0] => 70665 )

And I got as value the last value from array 70665.

Moshkopp
  • 23
  • 3
  • see this: http://stackoverflow.com/questions/11727746/how-do-i-fill-an-array-inside-a-while-loop-and-get-new-scope-each-iteration – Ori Price Jun 14 '16 at 09:52
  • If using a loop approach (and I'm not sure that you should), you could simply compare the current value with the previous value, and take the higher (and lower) of the two. – Strawberry Jun 14 '16 at 10:37

1 Answers1

2

Just use MIN and MAX query

SELECT MIN(Seriennummer) AS Min_Seriennummer, MAX(Seriennummer) AS Max_Seriennummer 
FROM  `seriennummern` WHERE GeraeteID = '$i'

And you get min and max value

$result1 = $mysqli->query($query1);
$countSN = $result1->num_rows;
while ($row = $result1->fetch_array()) {
    echo $min = $row['Min_Seriennummer'];
    echo $max = $row['Max_Seriennummer'];
}

Your code is open for sql injection check How can I prevent SQL injection in PHP? to prevent it

Community
  • 1
  • 1
Saty
  • 22,443
  • 7
  • 33
  • 51