在for / foreach循环中绑定pdo变量

在for / foreach循环中绑定pdo变量

问题描述:

I have looked at some other Stack Overflow questions on this, but I can't figure out how to loop through sql statements and bind variables to that. Here is how my queries look right now:

$db = dbCon();
$sql = "";
foreach($data as $d) {
    $sql .= "INSERT INTO required_fields (field_name) VALUES ($d)";
}
$stmt = $db->prepare($sql);
// Here is where I need to bind the variables
$stmt->execute();
$rowsChanged = $stmt->rowCount();
$stmt->closeCursor();
return $rowsChanged;

I can't figure out how to loop through because this is how I understand bindValue works:

$stmt->bindValue(':variableInQuery', $PHPVariable, PDO::PARAM_STR);

What's tripping me up is the colon in front of the variableInQuery and I can't figure out how to make the php variable name unique...what am I missing?

我已经看过其他一些Stack Overflow问题,但我无法弄清楚如何循环通过sql 语句和绑定变量。 以下是我的查询现在的样子:
p>

  $ db = dbCon(); 
 $ sql =“”; 
foreach($ data as $ d)  {
 $ sql。=“INSERT INTO required_fields(field_name)VALUES($ d)”; 
} 
 $ stmt = $ db-> prepare($ sql); 
 //这是我需要的地方 绑定变量
 $ stmt-> execute(); 
 $ rowsChanged = $ stmt-> rowCount(); 
 $ stmt-> closeCursor(); 
return $ rowsChanged; 
  code>   pre> 
 
 

我无法弄清楚如何循环,因为这是我理解bindValue的工作原理:
p>

  $ stmt-  > bindValue(':variableInQuery',$ PHPVariable,PDO :: PARAM_STR); 
  code>  pre> 
 
 

让我感到震惊的是变量前面的冒号,我可以 弄清楚如何使php变量名称唯一...我缺少什么? p> div>

You need to move the code inside the loop:

<?php
$db = dbCon();
$sql = "INSERT INTO required_fields (field_name) VALUES (:variableInQuery)";
$stmt = $db->prepare($sql);
$rowsChanged = 0;
foreach($data as $d) {
    $stmt->bindValue(':variableInQuery', $d, PDO::PARAM_STR);
    $stmt->execute();
    $rowsChanged += $stmt->rowCount();
}
$stmt->closeCursor();
return $rowsChanged;