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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀