Skip to content
PHP Logo

What are best practices for structuring INSERT queries with multiple values in PHP?

When inserting multiple values into a database using PHP, it is best practice to use prepared statements to prevent SQL injection attacks and improve performance. This can be achieved by preparing the INSERT query with placeholders for the values, binding the parameters to the placeholders, and executing the query within a loop for each set of values.

php
// Sample code for inserting multiple values into a database using prepared statements

// Database connection
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");

// Sample data to be inserted
$data = [
    ['John', 'Doe', 'john.doe@example.com'],
    ['Jane', 'Smith', 'jane.smith@example.com'],
    ['Alice', 'Johnson', 'alice.johnson@example.com']
];

// Prepare INSERT query
$stmt = $pdo->prepare("INSERT INTO users (first_name, last_name, email) VALUES (?, ?, ?)");

// Bind parameters and execute query for each set of values
foreach ($data as $row) {
    $stmt->execute($row);
}