使用MySQLi在PHP中使用多个Prepared语句

前端之家收集整理的这篇文章主要介绍了使用MySQLi在PHP中使用多个Prepared语句前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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

基本上我只想在一个表中插入一条记录,然后使用MysqLi将同一条记录插入另一个表中.

谢谢!

最佳答案
直接关闭MysqLi页面http://php.net/manual/en/mysqli.commit.php

PHP
$MysqLi = new MysqLi("localhost","my_user","my_password","world");

/* check connection */
if (MysqLi_connect_errno()) {
    printf("Connect Failed: %s\n",MysqLi_connect_error());
    exit();
}

/* 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',11.2)");

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

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

*编辑准备好的“非理智”行动声明:

PHP
$MysqLi = new MysqLi("localhost","root","","");

/* check connection */
if (MysqLi_connect_errno()) {
    printf("Connect Failed: %s\n",MysqLi_connect_error());
    exit();
}

/* 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);

if ($stmt1->execute() == false)
{
    echo 'First query Failed: ' . $MysqLi->error;
}
$stmt1->close();
if ($stmt2->execute() == false)
{
    echo 'Second query Failed: ' . $MysqLi->error;
}
$stmt2->close();
$MysqLi->close();

猜你在找的MySQL相关文章