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 使用ESP8266连接阿里云出现问题
  • ¥15 被蓝屏搞吐了,有偿求帮解答,Ai回复直接拉黑
  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并