Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple Prepared statements in PHP with MySQLi

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.

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

Thanks!

like image 416
David Avatar asked Mar 09 '12 20:03

David


People also ask

How run multiple MySQL queries in PHP?

Multiple statements or multi queries must be executed with mysqli::multi_query(). The individual statements of the statement string are separated by semicolon. Then, all result sets returned by the executed statements must be fetched.

What is a mysqli prepared statements?

A prepared statement is a feature used to execute the same (or similar) SQL statements repeatedly with high efficiency. Prepared statements basically work like this: Prepare: An SQL statement template is created and sent to the database.

What is $STMT in PHP mysqli?

" $stmt " obviously (I think) stands for "statement". As a variable name it's arbitrary, you can name that variable anything you want. $stmt is just rather idiomatic. A prepared statement as such is a database feature.

How write SQL query in multiple lines in PHP?

Multi-Line Strings can be written in PHP using the following ways. Using escape sequences: We can use the \n escape sequences to declare multiple lines in a string. PHP Code: PHP.


1 Answers

Directly off the mysqli page: 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);
like image 175
RumpRanger Avatar answered Sep 24 '22 03:09

RumpRanger