返回0 mysqli_affected_rows和mysqli_insert_id

时间:2017-05-11 11:52:41

标签: php function mysqli

我使用你的函数db_connect和db_query(),但我有一个问题:我如何使用mysqli_insert_id()和mysqli_affected_rows(),因为值返回0。

function db_connect(){
    static $connection;
        require_once __DIR__ . '/cfconfig.php'; 
    $connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE);
    $connection->set_charset('utf8');

    if (mysqli_connect_errno()) {
        printf("Connect failed: %s\n", mysqli_connect_error());
        exit();
    }
    return $connection;
}

function db_query($query) {
    $connection =  db_connect();
    $result = mysqli_query($connection,$query);
    return $result;
}

示例:

db_query("INSERT INTO  ....

之后:

$afectrows = mysqli_affected_rows(db_connect());
$insertid = mysqli_insert_id(db_connect());

值返回0

1 个答案:

答案 0 :(得分:2)

这是因为你的功能是它每次调用时都会创建新的连接,尽管有一些静态的变量存在变量。

要使其工作,您必须使您的连接真正静态

function db_connect(){
    static $connection;
    if (!$connection) {
        require_once __DIR__ . '/cfconfig.php'; 
        mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
        $connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE);
        $connection->set_charset('utf8');
    }
    return $connection;
}

现在您可以将插入ID设置为正确

$id = db_connect()->insert_id;