Tags
Asked 3 years ago
17 Jun 2021
Views 434
Bonnie

Bonnie posted

Insert Multiple Records Into MySQL from a multi line table PHP

Insert Multiple Records Into MySQL from a multi line table PHP
iptracker

iptracker
answered Apr 28 '23 00:00

Certainly, here's a possible rewrite:

To insert multiple records into a MySQL database from a multi-line table in PHP, you can use a loop to iterate over the lines of the table and execute a prepared INSERT statement for each row. Here's an example:



// Connect to the database
$dbh = new PDO("mysql:host=localhost;dbname=mydatabase", $user, $pass);

// Check connection
if ($dbh === false) {
    die("Connection failed.");
}

// Get the multi-line table data
$data = "John,Doe,25\nJane,Smith,30\nBob,Johnson,40\n";

// Split the table data into an array of rows
$rows = explode("\n", $data);

// Prepare the INSERT statement
$stmt = $dbh->prepare("INSERT INTO mytable (firstname, lastname, age) VALUES (:firstname, :lastname, :age)");

// Iterate over the rows and insert each one into the database
foreach ($rows as $row) {
    // Split the row into an array of values
    $values = explode(",", $row);

    // Bind the values to the placeholders
    $stmt->bindParam(':firstname', $values[0]);
    $stmt->bindParam(':lastname', $values[1]);
    $stmt->bindParam(':age', $values[2]);

    // Execute the statement
    if (!$stmt->execute()) {
        echo "Error: " . $stmt->errorInfo()[2] . "<br>";
    }
}

// Close the database connection
$dbh = null;

In this example, we first connect to the database using the PDO extension. Then, we get the multi-line table data as a string and split it into an array of rows using the explode() function. Next, we prepare the INSERT statement using placeholders (:firstname, :lastname, and :age) for the values.

Inside the foreach loop, we split each row into an array of values, and then bind those values to the corresponding placeholders in the prepared statement using bindParam() . Finally, we execute the statement using execute(), and check for errors using the errorInfo() method.

Note that using prepared statements with bound parameters helps prevent SQL injection attacks by ensuring that user input is properly sanitized. This can help protect your application from malicious attacks.
Post Answer