Moshkopp Moshkopp - 5 months ago 10
SQL Question

min and max value from array, gets always the same value

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.

Answer

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

Comments