MRustamzade MRustamzade -4 years ago 149
MySQL Question

Best practice inserting array to DB with PDO

I'm trying to add array content to database. For it i'm using

$arr = ["10","11","12","13"];

foreach ($arr as $value) {
$sql = "INSERT INTO `test` (user_id, view) VALUES (:user_id, :view)";
$stmt = $this->conn->prepare($sql);
$stmt->bindParam(':user_id', $value);
$stmt->bindParam(':view', 'small');
$stmt->execute();
}


is that good practice or bad? Is there any other good way?

Answer Source

Proper example is something like this:

$arr = ["10","11","12","13"];

$sql = "INSERT INTO `test` (`user_id`, `view`) VALUES (:user_id, :view)";
$stmt = $this->conn->prepare($sql);

foreach ($arr as $value) {
     $stmt->execute(array('user_id' => $value, 'view' => 'small'));
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download