【问题标题】:Mysqli SELECT FROM WHERE IFMysqli 选择从哪里如果
【发布时间】:2016-03-19 18:00:20
【问题描述】:
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?

【问题讨论】:

  • itemLeft > 0 看起来不错。它出什么问题了?错误?分享它。分享一切。
  • 它返回 false。但在我的数据库中 itemLeft 是 10

标签: php mysqli


【解决方案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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-05
    • 1970-01-01
    • 2016-05-18
    相关资源
    最近更新 更多