How to insert multiple rows in MySQL using PHP
In this tutorial, we are going to see how to insert multiple rows in MySQL using PHP. If you are a “newbie” you should know how to connect to a MySQL database before using the code below. You cannot insert data into a table if you are not connected to it.
How to insert multiple rows in MySQL using PHP
<?php
class InsertClass {
private $pdo;
public function __construct() {
// database connection
$this->pdo = new PDO("mysql:host = localhost; dbname = test", 'root', '');
}
function insert($name, $age, $address) {
$user = array(':name' => $name,
':age' => $age,
':address' => $address);
$sql = 'INSERT INTO users (
name,
age,
address
)
VALUES (
:name,
:age,
:address
);';
$query = $this->pdo->prepare($sql);
return $query->execute($user);
}
}
?>
We can now call the insert() method several times:
<?php
$obj = new InsertClass();
$obj->insert('Alex', 22, 'California'); // 1st insertion
$obj->insert('Bob', 25, 'Alaska'); // 2nd insertion
$obj->insert('Yohan', 30, 'Alabama'); // 3rd insertion
$obj->insert('Jean', 45, 'Arizona'); // 4th insertion
?>




