Choose the lowest price from the database row and ignore zero or 0

I have a database called prices, and there are 12 columns.

comp1, comp2, comp3, comp4, comp5, comp6, etc.

Then I want to run a query to find the lowest price stored on this line that matches the identifier, however I think it treats null as the lowest since I am not getting the correct answer.

Anyway, around this? or am i doing it wrong?

$query = "SELECT * FROM Prices WHERE id =$id" or die(mysql_error());
    $result = mysql_query($query) or die(mysql_error());
    while ($row = mysql_fetch_array($result)) {

    $comp1= $row['comp1'];
    $comp2= $row['comp2'];
    $comp3= $row['comp3'];
    $comp4= $row['comp4'];
    $comp5= $row['comp5'];
    $comp6= $row['comp6'];
    $comp7= $row['comp7'];
    $comp8= $row['comp8'];
    $comp9= $row['comp9'];
    $comp10= $row['comp10'];
    $comp11= $row['comp11'];
    $comp12= $row['comp12'];

$min = array( $comp1,  $comp2,  $comp3,  $comp4,  $comp5,  $comp6,  $comp7,  $comp8,  $comp8,  $comp10,  $comp11,  $comp12);

echo min($min);      

}
+3
source share
4 answers

If you call array_filter()in the array before the call min(), you clear everything that evaluates to false, including nulland 0.

For instance: $min = min(array_filter($min));

+8
source

Try:

$min = array( $comp1,  $comp2,  $comp3,  $comp4,  $comp5,  $comp6,  $comp7,  $comp8,  $comp8,  $comp10,  $comp11,  $comp12);
$min = array_filter($min);

echo min($min);    
+3

http://php.net/manual/en/function.min.php:

bugfree, NULL ( 0).

<?php
function min_mod () {
  $args = func_get_args();

  if (!count($args[0])) return false;
  else {
    $min = false;
    foreach ($args[0] AS $value) {
      if (is_numeric($value)) {
        $curval = floatval($value);
        if ($curval < $min || $min === false) $min = $curval;
      }
    }
  }

  return $min;  
}
?>
+1
source

Try the following:

$query = "SELECT * FROM Prices WHERE id =$id" or die(mysql_error());
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
    $i= 0;
    foreach ($row as $val) {
        if ($i == 0) {
            $tmpMin = $val;
        } else { 
            if ($tmpMin < $val) {
                $val = $tmpMin;    
            }
        }
    }

    unset($tmpMin);
    echo $tmpMin;
}
0
source

Source: https://habr.com/ru/post/1792309/


All Articles