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 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了
  • ¥100 H5网页如何调用微信扫一扫功能?
  • ¥15 讲解电路图,付费求解
  • ¥15 有偿请教计算电磁学的问题涉及到空间中时域UTD和FDTD算法结合的
  • ¥15 three.js添加后处理以后模型锯齿化严重
  • ¥15 vite打包后,页面出现h.createElement is not a function,但本地运行正常