insert cu numele coloanelor si valori din array asociativ

Discutii despre script-uri si coduri PHP-MySQL, precum si lucru cu XML in PHP.
andras
Mesaje: 430

insert cu numele coloanelor si valori din array asociativ

Salut,
Cum cconstruiesc o comanda INSERT eleganta dintr-un array asociativ cu $key - numele cimpului si $value-variabila POST? Multumesc.

MarPlo Mesaje: 4343
Salut,
Daca folosesti clasa PDO_MySQLi e cel mai indicat asa (fiindca are deja aceasta facilitate de a folosi valori din array, iar valorile transmise separat in array le filtreaza si pentru protectie sql injection).

Cod: Selectaţi tot

//cu clasa PDO_MySQLi
$arr =['col1'=>'val 1', 'col2'=>'val 2', 'col3'=>'val 3'];
$cols = array_keys($arr);  //get the keys
$sql ="INSERT INTO table_nm (". implode(', ', $cols) .") VALUES ( :". implode(', :', $cols) .")";

//test
echo $sql;  // INSERT INTO table_nm (col1, col2, col3) VALUES ( :col1, :col2, :col3)

//perform the $sql with placeholders in the SQL, and array with values for associated names
$conn->sqlExec($sql, $arr);
if($conn->error === false) echo 'Data succesfully inserted';
else echo 'Error: '. $conn->error; 
Alta varianta, fara clasa PDO_MySQLi:

Cod: Selectaţi tot

$arr =['col1'=>'val 1', 'col2'=>'val 2', 'col3'=>'val 3'];
$cols = implode(', ', array_keys($arr));  //get the keys
$vals = "'". implode("', '", array_values($arr)) ."'";  //get the values
$sql ="INSERT INTO table_nm ( $cols ) VALUES ( $vals )";

//test
echo $sql;  // INSERT INTO table_nm ( col1, col2, col3 ) VALUES ( 'val 1', 'val 2', 'val 3' ) 

andras Mesaje: 430
Folosesc clasa PDO_MySQLi dar imi sint utile ambele variante.

Subiecte similare