PHP MySQL Insert Multiple Records

Inserting multiple records into a MySQL table using PHP involves executing a SQL query that inserts multiple rows of data into the table. Here’s an example of how to insert multiple records into a MySQL table using PHP:

<?php
// MySQL server configuration
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydatabase";
// Create a connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check the connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
// Insert multiple records into the table
$sql = "INSERT INTO users (firstname, lastname, email) VALUES
        ('John', 'Doe', 'john@example.com'),
        ('Jane', 'Doe', 'jane@example.com'),
        ('Bob', 'Smith', 'bob@example.com')";
if (mysqli_query($conn, $sql)) {
    echo "Data inserted successfully";
} else {
    echo "Error inserting data: " . mysqli_error($conn);
}
// Close the connection
mysqli_close($conn);
?>

In this example, we first define the configuration for the MySQL server by specifying the server name, username, and password. We also specify the name of the database we want to work with in the $dbname variable. We then create a connection to the server and select the appropriate database using the mysqli_connect() function.

Next, we define the data we want to insert into the table in the $sql variable using SQL syntax. In this example, we insert three new rows of data into a table called “users” with values for the firstname, lastname, and email columns.

We then execute the SQL query using the mysqli_query() function and check if it was successful. If it was successful, we print a message indicating that the data was inserted successfully. Otherwise, we print an error message with the details of the error using the mysqli_error() function.

Finally, we close the connection using the mysqli_close() function.