简体   繁体   English

PHP PDO检查数据库查询是否返回NULL值

[英]PHP PDO Check if database query returns NULL values

I have a PHP function that makes a query to the database. 我有一个PHP函数,可以查询数据库。 I want if the query returns NULL Values the function to return false. 我想如果查询返回NULL值该函数返回false。 empty($result) does not work.

    $query = $this->dbh->prepare($sql);
    $query->bindParam(':phone', $phone);
    $query->bindParam(':name', $name);
    $result = $query->execute();
    if ($result) {
        if ($isVitamin) {
            $result_table = $query->fetch(PDO::FETCH_ASSOC);
            $result_table['isVitamin'] = 1;
            if (empty($result)) {
                return false;
            } else {
                return $result_table;
            }
        } else {
            $result_table = $query->fetch(PDO::FETCH_ASSOC);
            if (empty($result)) {
                return false;
            } else {
            //  echo "inside else";
            //  echo $result_table['name'];
                $result_table['isVitamin'] = 0;
                return $result_table;
            }
        }
    }  else {
        return false;
    }

Query returns null values. 查询返回空值。 Function does not return FALSE 函数不返回FALSE

在此输入图像描述

If I am not mistaken, you are using "$result" where you should be using "$result_table" - check the comment below: 如果我没弄错,你使用“$ result”,你应该使用“$ result_table” - 检查下面的评论:

$query = $this->dbh->prepare($sql);
$query->bindParam(':phone', $phone);
$query->bindParam(':name', $name);
$result = $query->execute();
if ($result) {
    if ($isVitamin) {
        $result_table = $query->fetch(PDO::FETCH_ASSOC);
        $result_table['isVitamin'] = 1;
        if (empty($result)) {
            return false;
        } else {
            return $result_table;
        }
    } else {
        $result_table = $query->fetch(PDO::FETCH_ASSOC);
        if (empty($result)) { //<-- this should be $result_table ?
            return false;
        } else {
        //  echo "inside else";
        //  echo $result_table['name'];
            $result_table['isVitamin'] = 0;
            return $result_table;
        }
    }
}  else {
    return false;
}

而不是If(空($ result))使用If(!$ result)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM