Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP PDO: How to insert multiple rows?

Tags:

sql

php

pdo

I've many sql statements but I want but I wonder if there is any method or function to shorten and do it in the fewest possible lines using PHP PDO.

One idea I have is to create an array with the following names: Perfiles, Usuarios, Customer, Mps, Poliza and Servicios together something like a foreach but I have no concrete idea, could you help me?

SQL STATEMENTS

$sqlpermsPer = "INSERT INTO t_perfiles_permisos (Id_Perfil, Area_Permiso, Buscar, Crear, Eliminar, Modificar)
                                            VALUES ($idPerfil,'Perfiles',0,0,0,0)";
$resultpermsPer = $this->dbConnect->query($sqlpermsPer) or die ($sqlpermsPer);

sqlpermsC = "INSERT INTO t_perfiles_permisos (Id_Perfil, Area_Permiso, Buscar, Crear, Eliminar, Modificar)
                                            VALUES ($idPerfil,'Clientes',0,0,0,0)";
$resultpermsC = $this->dbConnect->query($sqlpermsC) or die ($sqlpermsC);

$sqlpermsU = "INSERT INTO t_perfiles_permisos (Id_Perfil, Area_Permiso, Buscar, Crear, Eliminar, Modificar)
                                            VALUES ($idPerfil,'Usuarios',0,0,0,0)";
$resultpermsU = $this->dbConnect->query($sqlpermsU) or die ($sqlpermsU);

$sqlpermsM = "INSERT INTO t_perfiles_permisos (Id_Perfil, Area_Permiso, Buscar, Crear, Eliminar, Modificar)
                                            VALUES ($idPerfil,'Mps',0,0,0,0)";
$resultpermsM = $this->dbConnect->query($sqlpermsM) or die ($sqlpermsM);

$sqlpermsP = "INSERT INTO t_perfiles_permisos (Id_Perfil, Area_Permiso, Buscar, Crear, Eliminar, Modificar)
                                            VALUES ($idPerfil,'Poliza',0,0,0,0)";
$resultpermsP = $this->dbConnect->query($sqlpermsP) or die ($sqlpermsP);

$sqlpermsS = "INSERT INTO t_perfiles_permisos (Id_Perfil, Area_Permiso, Buscar, Crear, Eliminar, Modificar)
                                            VALUES ($idPerfil,'Servicio',0,0,0,0)";
$resultpermsS = $this->dbConnect->query($sqlpermsS) or die ($sqlpermsS);

Thanks in advance!

like image 657
SoldierCorp Avatar asked Nov 03 '22 17:11

SoldierCorp


1 Answers

This creates an array containing your strings, and loops through them, executing the same query with the bound parameters each time.

$stmt = $this->dbConnect->prepare("INSERT INTO t_perfiles_permisos (Id_Perfil, Area_Permiso, Buscar, Crear, Eliminar, Modificar) VALUES (:idPerfil,:str,0,0,0,0)");
$stmt->bindParam(':idPerfil', $idPerfil);
$stmt->bindParam(':str',$val);
$in_arr = array("Perfiles","Clientes","Usuarios","Mps","Poliza","Servicio");

foreach ($in_arr as $key => $val) {
    $stmt->execute();
}  
like image 53
Daedalus Avatar answered Nov 09 '22 13:11

Daedalus