drwiupraq047311240 2011-07-18 17:41
浏览 61
已采纳

在php foreach循环中获取$ _POST名称和值以构建一个长字符串

I need to put alot of radio button values into the database, so I post 300 values to a processing page, where I need to sort things out a bit.

I want to be able to differentiate between each radio buttons value and name (when posted) so I can insert them into the database. This is my code: (but maybe i need a jagged array?)

VALUE:

foreach ($_POST as $key => $value)
{
$value = $value.',';
}

POST NAME: ???

foreach ($_POST[name]?? as ??? => $postname)
{
$postname = $postname.',';
}

Then I need to differentiate between the value and name and put in the correct columns in the database:

mysql_query("INSERT INTO tabke SELECT '$longstring' or die(mysql_error());;  
  • 写回答

2条回答 默认 最新

  • doulao7572 2011-07-18 17:59
    关注

    I don't know why you want to insert using SELECT, as this construct is to insert from already existing table data. You can, however, insert multiple VALUES with a single statement. You'd need to do :

    // you should filter out values from your $_POST...
    $ignoredFields = array('submit', ...);
    $fields = array_intersect_key($_POST, array_flip($ignoredFields));
    
    $values = array();
    foreach ($fields as $key => $value) {
       $key = mysql_real_escape_string($key);
       $value = mysql_real_escape_string($value);
       $values[] =  "'{$key}', '{$value}'";
    }
    
    // creation the insert string
    $query = 'INSERT INTO `tabke` (`key`,`value`) VALUES ('.implode(,'),(', $values).')';
    $result = mysql_query($query);
    

    ** Note ** : I suppose that your table tabke look something like

    +---------+------------------+------+-----+---------+----------------+
    | Field   | Type             | Null | Key | Default | Extra          |
    +---------+------------------+------+-----+---------+----------------+
    | id      | int(10) unsigned | NO   | PRI | NULL    | auto_increment | 
    | key     | varchar(64)      | NO   |     | NULL    |                | 
    | value   | text             | NO   |     | NULL    |                | 
    +---------+------------------+------+-----+---------+----------------+
    

    As long as your query does not extend max_allowed_packet, this will work just fine. In case your data exceed that size, you can simply use array_chunk and iterate through the chunks and building the INSERT with each chunks.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求TYPCE母转母转接头24PIN线路板图
  • ¥100 国外网络搭建,有偿交流
  • ¥15 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型