使用数组的PDO bindParam,不按假设工作

时间:2015-04-18 12:27:26

标签: php mysql pdo bindparam

我有以下代码......

$statement = $conn->prepare("insert into logtest (course, date, time, distance,
      actualstarttime, finishtime, fav, favtotalmatched, favwma, 2ndfav,
      2ndfavtotalmatched, 2ndfavwma, 3rdfav, 3rdfavtotalmatched, 3rdfavwma,
      orangeflag, greenflag, betplaced, totalracetime, numcalculations,
      secswaitedbeforemonitoring, monitorstarttime, totalmonitoringtime)
      values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);");

    for($i = 0; $i < 23; $i++){
        $statement->bindParam($i + 1, $record[$i]);
    }

    $recordsprocessed = 0;

    $line = fgets($file); // Do this once before the loop to go past
                          // the column headers line

    while (!feof($file)){
        $line = fgets($file);
        $record = explode(",", $line);
        print_r($record);
        $statement->execute();
        ++$recordsprocessed;
    }

    echo "<p>Import finished.  $recordsprocessed records imported.</p>";

代码用空值填充数据库。我不明白为什么。我使用print_r来验证$record数组是否包含值。

从页面http://php.net/manual/en/pdo.prepared-statements.php可以看出,在这些变量包含值之前,参数可以绑定到变量,因此我假设我可以绑定到$record的项目,然后将这些值填入稍后循环。

我做错了什么?或者bindParam不能使用数组?

1 个答案:

答案 0 :(得分:1)

作为替代方案,您可以每行获取这些值,然后只需通过->execute()

添加这些批次
$query = 'INSERT INTO logtest 
    (course,date,time,distance,actualstarttime,finishtime,fav,favtotalmatched,favwma,2ndfav,2ndfavtotalmatched,2ndfavwma,3rdfav,3rdfavtotalmatched,3rdfavwma,
        orangeflag,greenflag,betplaced,totalracetime,numcalculations,secswaitedbeforemonitoring,monitorstarttime,totalmonitoringtime) 
        values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
';
$statement = $conn->prepare($query);

$recordsprocessed = 0;
$line = fgets($file);  // do this once before the loop to go past the column headers line
while (!feof($file)){

    $line = fgets($file);

    $record = explode(",",$line);

    $statement->execute($record);

    ++$recordsprocessed;
}

echo "<p>Import finished.  $recordsprocessed records imported.</p>";