Mysqli从中选择

时间:2016-03-19 18:00:20

标签: php mysqli

public function checkIfItemLeft($itemNameSecond){
        $query = "SELECT itemLeft 
                  FROM items
                  WHERE itemName = '$itemNameSecond' 
                  AND itemLeft > 0 Limit 1";
        if(mysqli_query($this->db->getDb(), $query)) {
            return true;
        }
        mysqli_close($this->db->getDb());
        return false;
    }

如何检查itemLeft是否大于0?

1 个答案:

答案 0 :(得分:1)

查询也可以像

一样完成
$query="SELECT CASE WHEN itemLeft>0 THEN 1 ELSE 0 END 
        FROM items 
        WHERE itemName = '$itemNameSecond'";
$result=mysqli_query($this->db->getDb(), $query);
if ($result) {  // the condition is necessary in case not record exists ...
  $row = mysqli_fetch_row($result);
  $largerthan0 = $row[0];  // will contain 1 if the value was >0
} 
else {
  $largerthan0 = 0;
}

想到更短的选择:

public function checkIfItemLeft($itemNameSecond){
 $query="SELECT COUNT(*) FROM items 
         WHERE itemName = '$itemNameSecond' AND itemLeft>0";
 $result=mysqli_query($this->db->getDb(), $query);
 $row = mysqli_fetch_row($result);
 return ($row[0]>0);
}
相关问题