开发者

Select lowest price from database row and ignore null or 0

I have a database called prices and there are 12 colum开发者_运维问答ns lets say.

comp1, comp2, comp3, comp4, comp5, comp6 and so on.

I then want to run a query to find the lowest price stored in that row that matches an id, however I think it is treating null as lowest value as I am not getting the correct answer.

Anyway around this? or am i doing this 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);      

}


If you call array_filter() on the array before calling min(), you will purge anything that evaluates to false, including null and 0.

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


Try:

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

echo min($min);    


From a comment in http://php.net/manual/en/function.min.php:

I've modified the bugfree min-version to ignore NULL values (else it returns 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;  
}
?>


Try this:

$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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜