Some prepared statements in PHP with MySQLi

I want to make two prepared statements, one after another in PHP with MySQLi. I am new to PHP and MySQLi, so I don’t know if I have to close the statement, close the database connection, put all the code in the function or just have the code inside the function.

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

Thanks!

+4
source share
2 answers

Directly leave the mysqli page: 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', 'Bavarian', 'F', 11.2)"); /* commit transaction */ $mysqli->commit(); /* close connection */ $mysqli->close(); 

* Edit using the prepared statements for the non-sane action:

 <?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(); 
+7
source

whether to close the operator

Not.

close database connection

Not.

put all the code in a function

It is preferable if you have an idea of ​​what functions and how to use them.

By the way, inserting the same data twice does not make sense. You should bind data, not double it.

+2
source

Source: https://habr.com/ru/post/1400651/


All Articles