Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP prepared statements and transactions in a loop [duplicate]

The classic transactions in a loop code:

$mysqli->query("START TRANSACTION");
foreach ($pdata as $key => $value) {
    $sql    = "INSERT INTO temp (`fund_id`) VALUES (" . $value . ")";
    $result = $mysqli->query($sql);
}
$mysqli->query("COMMIT");

Then we change to prepared statements:

$mysqli->autocommit(FALSE);
foreach ($pdata as $key => $value) {
    $sql  = "INSERT INTO temp (`fund_id`) VALUES (?)";
    $stmt = $mysqli->prepare($sql);
    $stmt->bind_param('i', $value);
    $stmt->execute();
}
$mysqli->commit();

Questions:

1) Are these two codes identical? Am I missing something in the second code with prepared statements?

2) Is $mysqli->commit() the same as $mysqli->query("COMMIT")?

3) Do I need to add $mysqli->query("START TRANSACTION"); for the prepared statements block or the transaction will automatically start when we set autocommit(FALSE)?

like image 284
user2723490 Avatar asked Oct 01 '13 02:10

user2723490


People also ask

What does Bind_param do in PHP?

Then, have a look at the bind_param() function: $stmt->bind_param("sss", $firstname, $lastname, $email); This function binds the parameters to the SQL query and tells the database what the parameters are. The "sss" argument lists the types of data that the parameters are.

What is $row in PHP?

Return Value: Returns an array of strings that corresponds to the fetched row. NULL if there are no more rows in result set. PHP Version: 5+

What is Mysqli_prepare?

Definition and Usage The prepare() / mysqli_prepare() function is used to prepare an SQL statement for execution.

Does MySQLi prevent SQL injection?

Parameterized queries solve SQL Injection vulnerabilities. This example uses PDO to fix the vulnerability but you can still use mysqli functions to prevent SQL Injection.


1 Answers

Your loop can be optimized by pulling the prepare and bind_param statements out of the loop.

$value = null;
$mysqli->autocommit(FALSE);
$sql  = "INSERT INTO temp (`fund_id`) VALUES (?)";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('i', $value);
foreach ($pdata as $value) {
    $stmt->execute();
}
$mysqli->commit();

You have turned off autocommit with your autocommit(FALSE) line and therefore don't need to use the START TRANSACTION statement.

like image 176
Andy Avatar answered Sep 20 '22 11:09

Andy