For people who might have issues understanding long rows of codes:
Make sure to have one array for each row to be inserted. Eg:
$data = [
['name'=>'Sam', 'job'=>'fullstack', 'device'=>'hp'],
['name'=>'Joey', 'job'=>'ui', 'device'=>'apple']
]
//the subarrays in $data can also be indexed arrays
The idea is to be able to easily form the SQL Insert query for multiple rows, which is supposed to look like this:
insert into table_name (col1, col2, col3) values ('valA1', 'valA2', 'valA3'), ('valB1', 'valB2', 'valB3'); //normal sql, insecure
insert into table_name (col1, col2, col3) values (?, ?, ?), (?, ?, ?); //prepared statement, secure
Hope I'm still making sense.
If you'll be doing this batch insert with dynamic column names, you must always have an array of the expected column names and assign default values to them. Eg:
$expectedcols = ['name'=>'', 'job'=>'', 'device'=>''];
Then;
$validcols = array_intersect_key($data[0], $expectedcols); //Takes only valid column names and throws away unexpected column names
$allvalidcols = array_merge($expectedcols, $validcols); //assigns the values in $validcols to the values in $expectedcols. Other columns in $expectedcols required to be inserted will also be captured, but their values will be those default values you assigned to them earlier.
$col_arr = array_keys($allvalidcols); //extracts the safe column names.
$columns = implode(', ', $col_arr); //name, job, device
$cols = count($col_arr); //number of columns, 3
$temparr = array_fill(0, $cols, '?'); //first set of placeholders ['?', '?', '?']
$tempstr = '('.implode(', ', $temparr).')'; //(?, ?, ?)
$rows = count($data); //number of rows, 2
$totalarr = array_fill(0, $rows, $tempstr); //full set of placeholders ['(?, ?, ?)', '(?, ?, ?)']
$totalstr = implode(', ', $totalarr); //(?, ?, ?), (?, ?, ?)
$allarr = [];
foreach($data as $ind=>$val) {
$values = array_values($val);
$allarr = array_merge($allarr, $values); //['Sam', 'fullstack', 'hp', 'Joey', 'ui', 'apple']
}
$sql = "insert into table_name ($columns) values $totalstr";
But if you are not doing the batch insert with dynamic column names, skip $validcols, $allvalidcols, $col_arr and $columns, they're not very necessary, then set $cols to the number of columns, which is 3 in this example, then adjust the $sql query to:
$sql = "insert into table_name (name, age, device) values $totalstr";
And finally;
$stmt = $conn->prepare($sql);
$done = $stmt->execute($allarr);
$stmt->execute($data);
php.net/manual/en/… Basically all of the params are passed validated as strings. Just loop through the data after building the query, and manuallybindValue
orbindParam
passing type as third-argument. – Harlotry