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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?