使用 MySQLi 在 PHP 中准备多个语句

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9640396/
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-26 07:20:18  来源:igfitidea点击:

Multiple Prepared statements in PHP with MySQLi

phpmysqlmysqliprepared-statement

提问by David

I want to do two prepared statements, one right after the other in PHP with MySQLi. I am a novice at PHP and MySQLi so I don't know whether I should close the statement, close the database connection, put all of the code in a function, or just have code not inside a function.

我想做两个准备好的语句,一个接一个在 PHP 中使用 MySQLi。我是 PHP 和 MySQLi 的新手,所以我不知道我是否应该关闭语句、关闭数据库连接、将所有代码放在一个函数中,或者只是在函数中没有代码。

Basically I just want to insert a record into one table and then insert the same record into another table using MySQLi.

基本上我只想在一个表中插入一条记录,然后使用 MySQLi 将相同的记录插入到另一个表中。

Thanks!

谢谢!

回答by RumpRanger

Directly off the mysqli page: http://php.net/manual/en/mysqli.commit.php

直接关闭mysqli页面:http: //php.net/manual/en/mysqli.commit.php

<?PHP
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$mysqli->set_charset('utf8mb4');

/* set autocommit to off */
$mysqli->autocommit(FALSE);

/* Insert some values */
$mysqli->query("INSERT INTO table1 VALUES ('DEU', 'Bavarian', 'F', 11.2)");
$mysqli->query("INSERT INTO table2 VALUES ('DEU', 'Bavarian', 'F', 11.2)");

/* commit transaction */
$mysqli->commit();

/* close connection */
$mysqli->close();

*Edit with prepared statements for "non-sane" action:

*使用“非理智”操作的准备语句进行编辑:

<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "root", "", "");
$mysqli->set_charset('utf8mb4');

/* set autocommit to off */
$mysqli->autocommit(FALSE);

$stmt1 = $mysqli->prepare("INSERT INTO tbl1 (id, intro) VALUES (?, ?)");
$stmt2 = $mysqli->prepare("INSERT INTO tbl2 (id, name) VALUES (?, ?)");

$str1 = 'abc';
$str2 = 'efg';
$str3 = 'hij';
$str4 = 'klm';

$stmt1->bind_param('ss', $str1, $str2);
$stmt2->bind_param('ss', $str3,$str4);

$stmt1->execute();
$stmt2->execute();

/* commit and set autocommit to on */
$mysqli->autocommit(true);

回答by Your Common Sense

whether I should close the statement

我是否应该关闭声明

No.

不。

close the database connection

关闭数据库连接

No.

不。

put all of the code in a function

将所有代码放在一个函数中

Preferably, if you have an idea what functions are and how to use them.

最好,如果您知道什么是函数以及如何使用它们。

BTW, inserting the same data twice makes no sense. You have to link data, not double it.

顺便说一句,两次插入相同的数据是没有意义的。你必须链接数据,而不是加倍。