dounielong7728 2016-08-01 19:04
浏览 78
已采纳

循环遍历变量数组并使用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];
    $cntr++;
}

$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] . ';');
        $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.

  • 写回答

1条回答 默认 最新

  • donglun4682 2016-08-01 20:07
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?