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

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

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

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

谢谢!

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

  1. PHP
  2. $MysqLi = new MysqLi("localhost","my_user","my_password","world");
  3. /* check connection */
  4. if (MysqLi_connect_errno()) {
  5. printf("Connect Failed: %s\n",MysqLi_connect_error());
  6. exit();
  7. }
  8. /* set autocommit to off */
  9. $MysqLi->autocommit(FALSE);
  10. /* Insert some values */
  11. $MysqLi->query("INSERT INTO table1 VALUES ('DEU','Bavarian','F',11.2)");
  12. $MysqLi->query("INSERT INTO table2 VALUES ('DEU',11.2)");
  13. /* commit transaction */
  14. $MysqLi->commit();
  15. /* close connection */
  16. $MysqLi->close();

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

  1. PHP
  2. $MysqLi = new MysqLi("localhost","root","","");
  3. /* check connection */
  4. if (MysqLi_connect_errno()) {
  5. printf("Connect Failed: %s\n",MysqLi_connect_error());
  6. exit();
  7. }
  8. /* set autocommit to off */
  9. $MysqLi->autocommit(FALSE);
  10. $stmt1 = $MysqLi->prepare("INSERT INTO tbl1 (id,intro) VALUES (?,?)");
  11. $stmt2 = $MysqLi->prepare("INSERT INTO tbl2 (id,name) VALUES (?,?)");
  12. $str1 = 'abc';
  13. $str2 = 'efg';
  14. $str3 = 'hij';
  15. $str4 = 'klm';
  16. $stmt1->bind_param('ss',$str1,$str2);
  17. $stmt2->bind_param('ss',$str3,$str4);
  18. if ($stmt1->execute() == false)
  19. {
  20. echo 'First query Failed: ' . $MysqLi->error;
  21. }
  22. $stmt1->close();
  23. if ($stmt2->execute() == false)
  24. {
  25. echo 'Second query Failed: ' . $MysqLi->error;
  26. }
  27. $stmt2->close();
  28. $MysqLi->close();

猜你在找的MySQL相关文章