如何检查mysql查询是否返回null

时间:2015-09-24 05:58:37

标签: php mysql

这里我想检查这个函数()中的查询是否返回null。

function ifproductValid($productID){
    $conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    } 
    $sql = "SELECT product_publish_status FROM product_list WHERE product_id='$productID'";
    $result = $conn->query($sql);
    if ($result->num_rows > 0) 
    {
        while($row = $result->fetch_assoc()) {      
            //here i want to check if the result is null or not
        if($product_status == 1){
            return true;
        } else {
            return false;
        }
        }       
        } else {
        echo "No results found";
    }
    $conn->close();
}

根据结果我想从此函数返回true或false。我怎么检查呢?

2 个答案:

答案 0 :(得分:1)

    while($row = $result->fetch_assoc()) {      
        if (is_null($row)) {
        // do something here
        }
    if($product_status == 1){
        return true;
    } else {
        return false;
    }
    }       
    } else {
    echo "No results found";

答案 1 :(得分:0)

只要您想从数据库中只获取一行,您就不需要花一些时间来迭代结果。我会做这样的事情:

function ifproductValid($productID){

    $conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
    $response = false;

    if($conn->connect_error){

        die("Connection failed: " . $conn->connect_error);
    }

    $sql = 'SELECT product_publish_status 
            FROM product_list WHERE product_id=' . $productID;
    $result = $conn->query($sql);

    if($result->num_rows > 0){

        $dbResult = $result->fetch_assoc();

        if(!is_null($dbResult[0] && $dbResult[0]['product_publish_status'] == 1){

            $response = true;
        }
    }

    $conn->close();
    return $response;
}

如果您只想确保数据库行永远不会为空,那么您可以在sql上指定它,这样您就不必在以后对其进行修改。

 $sql = 'SELECT product_publish_status 
         FROM product_list 
         WHERE product_id = ' . $productID . ' 
             AND product_publish_status IS NOT NULL';