![](/img/trans.png)
[英]PHP bound variables, Invalid parameter number error or PDO Update Statement
[英]Update in PDO/SQL with a variable number of variables :)
我有一个代码,可以检索以表单发送的所有输入数据。 如果表单仅填写了2个字段,则PHP仅获取这2个字段的值(不提交表单中未更改的字段)。
然后,我想为我用PHP代码检索到的那些字段更新SQL表。 这是我迷路的地方。 我只需要在SQL中指定从表单接收到的字段,但这是可变的。 也许我只收到1个字段,也许我收到了7个字段...
这是我的代码:
if (isset($_POST) && !empty($_POST)) {
echo $internalImage;
foreach ($_POST as $key => $value)
{
echo "Field Name: ".htmlspecialchars($key)." | Value: ".htmlspecialchars($value)."<br>";
}
}
你有什么建议?
您可以这样构造查询:
$values=array();
//this will be an array of possible fields that are in your table
$possible=array('field1', 'field2', 'field3');
$i=0;
$len=count($_POST);
$query='update table_name set ';
foreach($_POST as $key => $value){
$k=htmlspecialchars($key);
$v=htmlspecialchars($value);
if(in_array($k, $possible)){
$query .= $k .' = ?'; //placeholder for a value
$values[]=$v; //append values to an array for later use
if($i < ($len-1)) $query .= ', ';
$i++;
}
}
$query .= 'where table_id = ?';
$values[]=$table_id; //forgot that, append id of a row you are to update.
然后准备并执行查询:
$db->prepare($query);
$db->execute($query, $values);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.