dth62818 2013-12-18 21:59
浏览 38
已采纳

PHP / MSSQL; 根据数组索引是否存在数据插入记录

I have a PHP form with a structure like the following:

<input type="text" name="code[]" id="code[]" value="<?php echo $code[4] ?>" />
<input type="text" name="period[]" id="period[]" value="<?php echo $period[4]; ?>" />

There are five rows on my form with this structure. What I'm trying to do is, upon submit, ONLY insert records if the user enters data into these rows. Each row of input will produce a separate record. If the rows are blank, no record should be written. Right now, we have the INSERT statement in a for() loop, and it inserts blank records whenever the indexed field rows are empty. Here is what the INSERT statement looks like right now:

<?php
for($i=0; $i<=4; $i++) {
    $new = $con->prepare("INSERT INTO table (code, period) VALUES(:code, :period)");
    $data = array('code'=>$_POST['code'][$i],'period'=>$_POST['period'][$i]);
    $new->execute($data);
}
?>

Is there a way to accomplish what I'm trying to do?

  • 写回答

2条回答 默认 最新

  • duanchoupo1104 2013-12-18 22:09
    关注

    If you want insert only non-empty rows from your form, just check if there is something filled:

    <?php for($i=0; $i<=4; $i++) {
        if(isset($_POST['code'][$i]) && $_POST['code'][$i] != '' && 
           isset($_POST['period'][$i]) && $_POST['period'][$i] != ''){
              $new = $con->prepare("INSERT INTO table (code, period)
              VALUES(:code, :period)");
              $data = array('code'=>$_POST['code'][$i],'period'=>$_POST['period'][$i]);
              $new->execute($data);
        }
    } 
    ?>
    

    Notice, if you send blank fields they're set (isset returns true) but they are empty strings

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

报告相同问题?

悬赏问题

  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应