处理mysqli_query()返回值

时间:2015-04-10 09:14:44

标签: php mysql mysqli

我想自定义一个查询函数来处理mysqli_query在SELECT查询和其他查询(INSERT,UPDATE,DELETE)上的返回值。到目前为止,这是我的代码。

function db_query($sql) {

    $mysql_host = "localhost";
    $mysql_user = "root";
    $mysql_password = "";
    $mysql_database = "xxx";

    $conn = mysqli_connect($mysql_host, $mysql_user, $mysql_password, $mysql_database);

    if($result = mysqli_query($conn, $sql)){
        // Added -----------------------------------
        if($result === true){
            $rows = "success";
        }
        //------------------------------------------
        else if(mysqli_num_rows($result) > 0){
            while($row = mysqli_fetch_assoc($result)){
                $rows[] = $row;
           }
        }
        else if(mysqli_num_rows($result) == 0){
            $rows = "";
        }
    }
    else{
        echo "invalid query";
    }

    return $rows;

    mysqli_free_result($result);

    mysqli_close($conn);
}

如果查询(INSERT,UPDATE,DELETE)为true,我如何控制mysqli_query返回值?

引自http://php.net/manual/en/mysqli.query.php

  

失败时返回FALSE。成功的SELECT,SHOW,DESCRIBE或   EXPLAIN查询mysqli_query()将返回一个mysqli_result对象。对于   其他成功的查询mysqli_query()将返回TRUE。

0 个答案:

没有答案