【问题标题】:Update multiple images in PHP在 PHP 中更新多个图像
【发布时间】:2019-04-12 08:48:24
【问题描述】:

我遇到了一些关于在 PHP 中更新多个图像的问题。 实际上,我有 8 个用于添加和更新图像的 8 个按钮以及 MySQL 数据库中的 8 个单独的列,所以当我单独更新图像时,它要么更新所有 8 个列的值,即使我只选择 image1 和 image2,它也会更新所有列和 image3 到 image7 将在数据库中包含空值

如果我使用&& 'AND' 运算符

或者它不更新列图像的任何值(image, image1, image2,.... image7)

如果我使用|| 'OR' 运算符

但我真正想要的是,如果我想更新 image1 - image8 中的任何图像,只有该图像应该得到更新,并且数据库中的其余值应该与以前的值相同,即图像列中的值是图像的名称。

if(empty($image) && empty($image1) && empty($image2) && empty($image3) && empty($image4) && empty($image5) && empty($image6) && empty($image7) ){

        $UpdateSql = "UPDATE car SET mobile='$mobile' WHERE id=$id";

        $result = mysqli_query($conn, $UpdateSql);

    }else{

        $UpdateSql = "UPDATE car_list SET mobile='$mobile', image='$image', image1='$image1',image2= '$image2', image3='$image3',image4='$image4',image5='$image5', image6='$image6',image7='$image7' WHERE id=$id";

        $result = mysqli_query($conn, $UpdateSql);

    }

【问题讨论】:

  • 我可能建议您在这里犯了一个数据库设计错误。图片应该在一个单独的表格中,使用它的 id 链接到car_list
  • 您的脚本对SQL Injection Attack 甚至if you are escaping inputs, its not safe! 都是开放的,在MYSQLI_PDO API 中使用prepared parameterized statements
  • 其实这样存储手机号码也是个坏主意
  • @RiggsFolly 能否请您举例说明如何更新它?
  • @RiggsFolly 实际上是在堆栈溢出时询问查询,我刚刚编写了示例代码,但我提供了安全性:)

标签: php mysql arrays mysqli


【解决方案1】:

您需要根据图像变量的值来构建 SQL 查询。例如:

$mobile = "someMobileNo";
$id = 1234;

$image = "";
$image1 = "";
$image2 = "some.png";
$image3 = "";
$image4 = "";
$image5 = "someOther.png";
$image6 = "yetAnother.png";
$image7 = "";

$imageVars = array($image, $image1, $image2, $image3, $image4, $image5, $image6, $image7,);

$updateImages = "";

for($i = 0; $i < 8; $i ++){
    if(!empty($imageVars[$i])){
        //the image variable has a value, add it to the UPDATE query
        $imageNum = (string)$i; //cast index as string
        if($imageNum == "0"){
            //first image does not have a number
            $imageNum = "";
        }
        $updateImages .= ",image" . $imageNum . "='" . $imageVars[$i] . "'";
    }
}

$UpdateSql = "UPDATE car_list SET mobile='$mobile'" . $updateImages . " WHERE id=$id";

echo $UpdateSql;


//OUTPUT:
//    UPDATE car_list SET mobile='someMobileNo',image2='some.png',image5='someOther.png',image6='yetAnother.png' WHERE id=1234

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-09
    • 2016-04-15
    • 1970-01-01
    • 2020-03-03
    • 1970-01-01
    • 1970-01-01
    • 2013-11-26
    相关资源
    最近更新 更多