how to insert data from an array into a table

1

Hello good afternoon, I have been trying to solve a problem for a while

I'll explain:

I have a form that when I send the data I store it in an associative array to pass it in the constructor of the class since there are many variables and I do not want to load the constructor of so many variables and I do not want to create so many attributes in the class, the array has 37 variables with their respective keys, the question is: How do I store each data of that array in each column of the table? I would appreciate your valuable help greetings

    
asked by Diego Fajardo 31.01.2018 в 21:26
source

1 answer

0

Following the idea of the comment, a simple implementation may be the following

$parametros_post = array(
  'p1' => 'valor',
  'p2' => 'valor2'
);
//suponiendo una conexión de bd abierta
$campos = '';
$parametros = '';
$parametros_consulta = array();
foreach($parametros_post as $nombre_parametro => $valor_parametro) {
  //validar datos, etc.
  $campos .= "$nombre_parametro,";
  $parametros .= ":$nombre_parametro,";
  $parametros_consulta[":$nombre_parametro"] = $valor_parametro;
}

$campos = trim($campos, ',');
$parametros = trim($parametros, ',');

$insert = "INSERT INTO tabla($campos) VALUES($parametros)";

echo $insert;

//preparar instrucción y ejecutar pasando como parametro el array $parametros_post y la conexión 
    
answered by 01.02.2018 / 01:44
source