duancaiyi7567 2012-12-29 21:54
浏览 24
已采纳

如何遍历$ _POST数组并将数据发送到不同的MySQL表

I have a form that will send data via POST. I want that data to go to different MySQL tables based on the POST "name."

What I have so far is a while loop for the form fields that will name each input in the format: "name"{}$id. I thought that using {} as a delimiter I could then use explode() and use a conditional statement to select which table the data should go to.

Is this the best way to do this? The issue I'm having is also calling the name, since using foreach for example on POST will just return the values and not the names. I have enclosed the code below:

<?php while ($cred = mysql_fetch_array($credentials_process)) { ?>
    <div class="edit-profile-background-inputs">
        <span><input type="text" name="cred{}<?php echo $cred['id']; ?>" value="<?php echo $cred['credentials']; ?>" /></span>
        <span style="margin-left:10px;"><a href="<?php echo "background.php?cred=".$cred['id']; ?>">Remove</a></span>
    </div>
    <?php } ?>

I need those fields named cred{} to go to credentials table, those named edu{} to go to the education table, etc.

  • 写回答

1条回答 默认 最新

  • douyou8047 2012-12-29 22:01
    关注
    <input type="text" name="cred[<?php echo $cred['id']; ?>]"...
    <input type="text" name="edu[<?php echo $edu['id']; ?>]"...
    

    in PHP

    $insert=array();
    foreach ($_POST['cred'] as $k=>$v)
    {
        $insert[$k]=mysql_real_escape_string($v); // yes I know mysql is being depreciated
    }
    
     $sql='INSERT INTO cred ('. implode(',', array_keys($insert)).') VALUES ('. implode(',', $insert).');
    

    repeat for $_POST['edu']

    If your results set is such that you're outputting more than one row with the same key

    $i=0;
    while ($cred = mysql_fetch_array($credentials_process)) { ?>
        <input type="text" name="cred[$i][<?php echo $cred['id']; ?>]"...
        ...
        $i++;
    }
    

    If you print_r($_POST) from that you'll be able to figure out how to deal with them.

    NB. For safety I would also make sure only the expected posted vars get used

    $allowed=array('cred_id', 'cred_something', 'etc');
    
    foreach ($_POST['cred'] as $k=>$v){
        if (!in_array($k, $allowed)) continue;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测