php - How to use MySQLi prepared statements to execute multiple INSERTs with variable number of placeholders? -
php - How to use MySQLi prepared statements to execute multiple INSERTs with variable number of placeholders? -
any ideas how utilize mysqli prepared statements execute multiple inserts
while having variable number (around 40) of placeholders?
i know how create prepared statements variable number of placeholders:
array_unshift($paramvalues, str_repeat('s', count($paramvalues))); call_user_func_array( [$statement, 'bind_param'], sql::makevaluesreferenced($paramvalues) );
i know how create multiple executions:
$statement->bind_param('i', $id); ($id=0, $id<10, ++$id) { $statement->execute(); }
but couldn't wrap mind plenty combine both methods single one.
basically, have array total of info want insert database without having manualy hardcode variables. want function set array info , function take care of binding , executing.
$data = [ 0 => [a => aaa, b => bbb], 1 => [a => ccc, b => ddd], ];
(i using php 5.5 , mysql 5.5.)
quite prepare sql 1 time , repeat bind_param()
, execute()
multiple times. although think got that.
so using illustration input
$data = [ 0 => [a => aaa, b => bbb], 1 => [a => ccc, b => ddd], ];
.
// list of field names // , build question mark list $fields = ''; $qmarks = ''; foreach ( $data[0] $field => $val ) { $fields .= $field . ','; $qmarks .= '?,'; } rtrim($fields, ','); rtrim($qmarks, ','); /* build datatype list: replace commas nil , ? s work if datatypes same if had datatypes in $data array work better, or rather more flexible think fly in ointment!! */ $datatypes = ''; $datatypes = str_replace(array(',','?'),array('','s'),$qmarks); $sql = "insert table table ($fields) values($qmarks)"; $stmt = $db->prepare($sql); foreach ($data $row ) { $params = array(); foreach ( $row $name => $val ) { $params[] = $val; } $stmt->bind_param($datatypes, $params); $result = $stmt->execute(); if ( ! $result ) { // have error, deal here , stop loop } }
php mysql prepared-statement
Comments
Post a Comment