Don't forget to hit the ⭐ if you like this repo.
To do this, include multiple lists of column values within the INSERT INTO statement, where column values for each row must be enclosed within parentheses and separated by a comma. Database: demo1, table: persons.
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "demo1");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt insert query execution
$sql = "INSERT INTO persons (first_name, last_name, email) VALUES
('Rifadul', 'Islam', 'rif@mail.com'),
('Iqbal', 'Muzakki', 'iqbal@mail.com'),
('Irma Zafirah', 'Mohd Ikram', 'irma@mail.com'),
('Noor Arinie', 'Norhalil', 'arinie@mail.com')";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>
-
The code begins by assigning an SQL query string to the variable
$sql
. In this case, the query is an INSERT INTO statement for the tablepersons
. The columns specified in the query arefirst_name
,last_name
, andemail
. -
The VALUES clause contains multiple sets of values, each enclosed in parentheses and separated by commas. Each set represents a row to be inserted into the table. In this code, four rows are being inserted with the corresponding values for
first_name
,last_name
, andemail
. -
The
mysqli_query()
function is used to execute the SQL query. It takes two parameters: the connection object ($link
) representing the connection to the MySQL server, and the SQL query string ($sql
) that needs to be executed. -
If the
mysqli_query()
function returnstrue
, indicating that the query was executed successfully, the code inside theif
block is executed. In this case, it prints the message "Records added successfully." using theecho
statement, indicating that the insertion of multiple rows was successful. -
If the
mysqli_query()
function returnsfalse
, indicating an error in executing the query, the code inside theelse
block is executed. It uses themysqli_error()
function to retrieve the specific error message from the MySQL server, concatenates it with the error message "ERROR: Could not able to execute $sql.", and then prints the concatenated error message using theecho
statement.
By using this code, you can insert multiple rows of data into the "persons" table in the MySQL database and receive appropriate feedback regarding the success or failure of the insertion query execution.
Please create an Issue for any improvements, suggestions or errors in the content.
You can also contact me using Linkedin for any other queries or feedback.