我有一个代码可以检索表单中发送的所有输入数据。如果表单只填写了2个字段,那么PHP只获得这两个字段的值(表单中未更改的字段未提交)。
然后我想为我用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>";
}
}
你会建议什么?
答案 0 :(得分:0)
您可以像这样构建查询:
$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);