Asked 3 years ago
17 Jun 2021
Views 643
Jalon

Jalon posted

insert multiple rows into database via form

insert multiple rows into database via form
shabi

shabi
answered Apr 28 '23 00:00

Here's an example of how to insert multiple rows into a MySQL database via a form using PHP:

HTML form:



<form action="insert.php" method="post">
  <input type="text" name="names[]" placeholder="Name">
  <input type="text" name="ages[]" placeholder="Age">
  <input type="text" name="emails[]" placeholder="Email">
  <input type="text" name="names[]" placeholder="Name">
  <input type="text" name="ages[]" placeholder="Age">
  <input type="text" name="emails[]" placeholder="Email">
  <input type="submit" value="Insert">
</form>
PHP code (insert.php):




<?php

// Get the form data
$names = $_POST['names'];
$ages = $_POST['ages'];
$emails = $_POST['emails'];

// Create a PDO object to connect to the database
$db = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

// Prepare the SQL statement for insertion
$sql = "INSERT INTO mytable (name, age, email) VALUES (:name, :age, :email)";

// Prepare the PDO statement for execution
$stmt = $db->prepare($sql);

// Loop through each set of form data and execute the prepared statement
for ($i = 0; $i < count($names); $i++) {
  $name = $names[$i];
  $age = $ages[$i];
  $email = $emails[$i];
  $stmt->bindParam(':name', $name);
  $stmt->bindParam(':age', $age);
  $stmt->bindParam(':email', $email);
  $stmt->execute();
}

// Close the database connection
$db = null;

// Redirect to a confirmation page
header('Location: confirmation.php');
exit();
?>

In this example, the form data is passed to the PHP script via arrays with the same name (names[], ages[], emails[]). The PHP script then loops through the arrays using a for loop and inserts each set of data into the MySQL database using a prepared statement with placeholders.

Note that you should always sanitize and validate user input to prevent security vulnerabilities, and you should consider implementing measures to prevent duplicate data entry (e.g. checking if the data already exists in the database before inserting it).
Post Answer