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.

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

报告相同问题?

悬赏问题

  • ¥15 matlab实现基于主成分变换的图像融合。
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊