How insert to mysql many rows using php?

Member

by kadin , in category: PHP General , 6 months ago

How insert to mysql many rows using php?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by cali_green , 6 months ago

@kadin 

To insert many rows into a MySQL database using PHP, you can use prepared statements and a loop to execute multiple insert queries. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// Sample data to insert
$data = array(
    array('John', 'Doe'),
    array('Jane', 'Smith'),
    array('Mark', 'Johnson')
);

// MySQL database connection parameters
$servername = 'localhost';
$username = 'your_username';
$password = 'your_password';
$database = 'your_database';

// Create a new PDO instance
try {
    $conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // Prepare the insert statement
    $stmt = $conn->prepare("INSERT INTO table_name (column1, column2) VALUES (:value1, :value2)");

    // Begin the transaction
    $conn->beginTransaction();

    // Loop through each row and execute the insert query
    foreach ($data as $row) {
        $stmt->bindParam(':value1', $row[0]);
        $stmt->bindParam(':value2', $row[1]);
        $stmt->execute();
    }

    // Commit the transaction
    $conn->commit();

    echo "Records inserted successfully!";
} catch (PDOException $e) {
    // Rollback the transaction if any error occurred
    $conn->rollback();
    echo "Error: " . $e->getMessage();
}

// Close the connection
$conn = null;


Make sure to replace table_name, column1, and column2 with the actual names of your table and columns. Also, update the database connection parameters according to your MySQL setup.

by elise_daugherty , 6 months ago

@kadin 

The code above demonstrates how to insert multiple rows into a MySQL database using PHP.


First, define the data that you want to insert in an array format.


Next, specify the MySQL database connection parameters, including the server name, username, password, and database name.


Create a new PDO instance with the connection parameters.


Prepare the insert statement using placeholders for the values that will be inserted.


Begin a transaction to ensure that the data is inserted as a single unit.


Loop through each row in the data array and execute the insert query. Bind the values for each row to the placeholders.


Commit the transaction once all rows have been inserted successfully.


If an error occurs during the insertion process, rollback the transaction to revert any changes.


Finally, close the database connection.


Remember to replace "table_name", "column1", and "column2" with your actual table name and column names.


This code provides a safe and efficient way to insert multiple rows into a MySQL database using PHP.