MySQLi PHP:使用 MySQLi 检查 SQL INSERT 查询是否完全成功

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2871866/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 07:59:13  来源:igfitidea点击:

MySQLi PHP: Check if SQL INSERT query was fully successful using MySQLi

phpmysqlsqlmysqli

提问by Jonathan

I have this big function that gets a lot of different data and insert it into multiple tables.. Not all the data is always available so not all the SQL INSERT queries are successful. I need to check which SQL INSERT query was fully successful and which wasn't to the do something with this data (like inserting into a log table or similar).

我有这个大函数,它可以获取大量不同的数据并将其插入多个表中。并非所有数据始终可用,因此并非所有 SQL INSERT 查询都成功。我需要检查哪个 SQL INSERT 查询完全成功,哪个不是对这些数据做些什么(比如插入日志表或类似的)。

Just to give you an example of how I think it can be done:

只是给你一个我认为如何做到的例子:

$sql = 'INSERT INTO data_table (ID, column1, column2) VALUES(?, ?, ?)';

if ($stmt->prepare($sql)) {
    $stmt->bind_param('iss', $varID, $var1, $var2);

    if ($stmt->execute()) {
        $success == TRUE;   //or something like that
    }
}

I'm not completely sure this is the best way and if its always really show if the data was inserted into the table... Any suggestions??

我不完全确定这是最好的方法,如果它总是真正显示数据是否插入表中......有什么建议吗?

回答by Alix Axel

From the PHP Manual on mysqli_stmt::execute:

从 PHP 手册上mysqli_stmt::execute

mysqli_stmt::execute-- mysqli_stmt_executeExecutes a prepared Query

Returns TRUE on success or FALSE on failure.

mysqli_stmt::execute-- mysqli_stmt_execute--执行一个准备好的查询

成功时返回 TRUE,失败时返回 FALSE。



if ($stmt->execute()) { // exactly like this!
    $success = true;
}

You're doing it right... What's your dilemma?

你做对了......你有什么困难?

回答by Salman A

I believe you can use mysqli_stmt->affected_rowsto return the number of rows inserted (or changed or deleted).

我相信您可以使用mysqli_stmt->affected_rows返回插入(或更改或删除)的行数。