dtn36013 2013-02-28 22:20
浏览 47
已采纳

使用可变数量的变量在PDO / SQL中更新:)

I have a code that retrieves all the input data sent in a form. If the form had only 2 fields filled out, the PHP gets the value for only those 2 fields (the unchanged fields in the form are not submitted).

Then I would like to UPDATE a SQL table for those fields that I have retrieved with my PHP code. Here is where I am lost. I would need to specify in the SQL only the fields that I have received from the form, but this is variable. Maybe I received only 1 field, maybe I received 7 of the fields...

Here is my code:

if (isset($_POST) && !empty($_POST))  {
echo $internalImage;

foreach ($_POST as $key => $value) 
    {
 echo "Field Name: ".htmlspecialchars($key)." | Value: ".htmlspecialchars($value)."<br>";
    }
}

What would you suggest?

  • 写回答

1条回答 默认 最新

  • dongtuoao7987 2013-02-28 22:37
    关注

    You could construct your query like this:

    $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.
    

    and then prepare and execute the query:

    $db->prepare($query);
    $db->execute($query, $values);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里