multiple_inserts.php
<?php
//Config
$server = "localhost";
$user = "root";
$password = "";
$database = "address_book";
//Establishing a Connection to MySQL Server
$connection = mysqli_connect($server, $user, $password, $database);
//Check Connection
if (!$connection) {
die("<h2>Total Fail</h2> " . mysqli_connect_error());
} else {
echo "Connection Successfull <br>";
}
//SQL Command
$sql_command = "INSERT INTO people (id, name, lastname, telephon, email, address)
VALUES (NULL, 'John', 'Smith', 555777, 'mailx@server.net', 'Main Road 12a');";
$sql_command .= "INSERT INTO people (id, name, lastname, telephon, email, address)
VALUES (NULL, 'Samantha', 'Smith', 111222, 'mailz@server.net', 'Main Road 12a');";
$sql_command .= "INSERT INTO people (id, name, lastname, telephon, email, address)
VALUES (NULL, 'Anabela', 'Smith', 555777, 'mailx@server.net', 'Main Road 12a')";
//Check SQL Command
if (mysqli_multi_query($connection, $sql_command)) {
$last_entry = mysqli_insert_id($connection);
echo "SQL Command OK, Last ID: " . $last_entry . "<hr>" ;
} else {
echo "SQL ERROR" . mysqli_error($connection);
}
?>
This PHP code creates a SQL command that inserts multiple rows into the people
table of the currently selected database.
The $sql_command
variable is a string that concatenates multiple INSERT
statements together.
Each INSERT
statement specifies the columns and values to be inserted into the table. The id
column is set to NULL
, which will automatically generate a new value for this column using the AUTO_INCREMENT
feature.
The mysqli_multi_query()
function is used to execute the SQL command. If the command is successful, the mysqli_insert_id()
function is used to retrieve the ID of the last inserted row.
The output will be either "SQL Command OK, Last ID: [ID]" if the command was successful or "SQL ERROR" if there was an error executing the command.
After we run it multiple times:
Connection Successfull
SQL Command OK, Last ID: 24
No comments:
Post a Comment