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 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么