envisteven envisteven - 1 year ago 61
PHP Question

Looping through a variable array and inserting using bind_param

Im trying to loop through several arrays to insert data into a mysql database. And Im trying to bind the data so that I can loop through it. There can be a various number of columns to which data is bound.

It appears that the data Im binding is not being processed as expected and the insert ultimately fails.

I have a columns array that stores the column names and data types. I also have a values array that stores the values that are to be inserted. Sample data:

$colArr = array (
array('i', 'ID'),
array('s', 'Date')

$valArr = array(
array(1, 'now()'),
array(2, 'now()'),

//I create my type and query strings as well as the array referencing the columns for binding.

$valStrForQry = rtrim(str_repeat('?, ', count($v['colArr'])), ', '); //result: '?, ?'
$params = array();
$colsForQry = '';
$typeStr = '';
$cntr = 0;
foreach ($colArr as $cols) {
$colsForQry .= $cols[1] . ', ';
$typeStr .= $cols[0];
$params[] = &$valArr[$cntr][1];

$colsForQry = rtrim($colsForQry, ', '); //result: 'ID, Date'

$qry = 'INSERT INTO table (' . $colsForQry . ') VALUES (' . $valStrForQry . ')';
$stmt = $mysqli->prepare($qry);

//Bind the parameters.

call_user_func_array(array($stmt, 'bind_param'), array_merge(array($typeStr), $params));

//Loop through the values array, assign them using eval, and execute the statement. Im open to suggestions if theres a better way to do this.

foreach ($valArr as $vals) {
$cntr = 0;
foreach ($colArr as $c) {
eval('$' . $c[1] . ' = ' . $vals[$cntr] . ';');

if ($stmt->execute() === FALSE) {
//show $stmt->error for this iteration
} else {
//show success for this iteration

The first iteration results in a successful insertion of incorrect data. That is, the inserted ID is 0, not 1, and no other info is inserted. The second iteration (and all consecutive ones) results in the following error message: Duplicate entry '0' for key 'PRIMARY'

What am I doing wrong here, is it the eval or something else? Im not sure how to figure this one out.

Answer Source

Instead of continuing to try to get the existing code working, I'm going to suggest a KISS starting point, without the prepare(), the eval(), or the bind_param().

  $cols = ['ID', 'Date'];
  $vals = [
    [1, '\'now()\''],
    [2, '\'now()\''],

  foreach ($vals as $val)
    $sql = 'INSERT INTO table (' . implode($cols, ', ') . ') VALUES (' . implode($val, ', ') . ')';
    // exec here

To make this a bit safer, you'll probably want to escape all the values before the implode, or before/as they are put into the array you're working with. The existing code is, IMHO, trying to be too "clever" to do something so simple.

Alternately, you may want to consider switching to using the PDO library instead of mysqli. PDO supports binding of named parameters on a per-parameter basis, which could be done in a loop without the eval().

Someone else may get the provided "clever" solution working instead of course.