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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?