duancong2965 2015-06-09 08:59
浏览 286
已采纳

PHP多个if语句只执行最后一个语句

I know similar questions have been asked a lot, and I have searched through and am unable to find an answer that fixes the problem I am having.

I have a form with multiple textareas that updates a mysql entry, and I would like PHP to make sure there is something in the textarea before updating the entry. This works when I only have one entry being updated, but when I do more than one at a time only the last one is updated. I tried using else if, and in that case only the first one is updated. How can I make it update all entries where text has been entered?

In my code the form input name matches the column name.

$value = $_POST['titleLeft'];
$value2 = $_POST['textLeft'];
$value3 = $_POST['imgName'];
$value4 = $_POST['titleRight'];
$value5 = $_POST['textRight'];

if (strlen($value) > 0){
    $sql = "UPDATE classesSpecial SET titleLeft = '$value' WHERE id = '1'";
}

if (strlen($value2) > 0){
    $sql = "UPDATE classesSpecial SET textLeft = '$value2' WHERE id = '1'";
}

if (strlen($value3) > 0){
$sql = "UPDATE classesSpecial SET imgName = '$value3' WHERE id = '1'";
}

if (strlen($value4) > 0){
    $sql = "UPDATE classesSpecial SET titleRight = '$value4' WHERE id = '1'";
}

if (strlen($value5) > 0){
    $sql = "UPDATE classesSpecial SET textRight = '$value5' WHERE id = '1'";
}
  • 写回答

3条回答 默认 最新

  • dthtvk3666 2015-06-09 09:04
    关注

    It's because you keep on overwriting $sql. One solution would be to do this for each post request:

    if((strlen($value) > 0) {
      $sql[] = "UPDATE classesSpecial SET titleLeft = '$value' WHERE id = 1";
    }
    

    $sql[] means you're adding values to an array, which you can later use to process all requests. Then, at the end of your script, you'll do this for executing your SQL:

    foreach($sql as $query) {
      mysqli_query($db, $query)or die(mysqli_error($db));
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退
  • ¥20 win系统的PYQT程序生成的数据如何放入云服务器阿里云window版?
  • ¥50 invest生境质量模块