0

我有一个代码可以检索表单中发送的所有输入数据。如果表单仅填写了 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>";
    }
}

你有什么建议?

4

1 回答 1

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);
于 2013-02-28T22:37:27.893 回答