HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

PHP MySQL Insert Multiple Records

To insert multiple records into a MySQL database using PHP, you can utilize prepared statements within a loop to efficiently execute multiple insertions.

Here's how to do it for both approaches:

Using MySQLi:

<?php
// MySQLi Configuration
$servername = "localhost"; // Change this to your MySQL server address
$username = "username"; // Change this to your MySQL username
$password = "password"; // Change this to your MySQL password
$database = "dbname"; // Change this to your MySQL database name

// Sample data to be inserted
$records = array(
    array("John Doe", "john@example.com"),
    array("Jane Smith", "jane@example.com"),
    array("Bob Johnson", "bob@example.com")
);

// Create connection
$conn = new mysqli($servername, $username, $password, $database);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// SQL statement
$sql = "INSERT INTO users (name, email) VALUES (?, ?)";

// Prepare and bind the statement
$stmt = $conn->prepare($sql);
$stmt->bind_param("ss", $name, $email);

// Execute multiple insertions within a loop
foreach ($records as $record) {
    $name = $record[0];
    $email = $record[1];
    $stmt->execute();
}

echo "Multiple records inserted successfully";

// Close connection
$stmt->close();
$conn->close();
?>
You can click on above box to edit the code and run again.

Output

Using PDO:

<?php
// PDO Configuration
$servername = "localhost"; // Change this to your MySQL server address
$username = "username"; // Change this to your MySQL username
$password = "password"; // Change this to your MySQL password
$database = "dbname"; // Change this to your MySQL database name

// Sample data to be inserted
$records = array(
    array("John Doe", "john@example.com"),
    array("Jane Smith", "jane@example.com"),
    array("Bob Johnson", "bob@example.com")
);

try {
    // Connect to MySQL using PDO
    $conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
    
    // Set PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // SQL statement
    $sql = "INSERT INTO users (name, email) VALUES (?, ?)";
    
    // Prepare the statement
    $stmt = $conn->prepare($sql);
    
    // Execute multiple insertions within a loop
    foreach ($records as $record) {
        $stmt->execute($record);
    }
    
    echo "Multiple records inserted successfully";
} catch(PDOException $e) {
    echo "Error: " . $e->getMessage();
}

// Close connection
$conn = null;
?>
You can click on above box to edit the code and run again.

Output