我有一个带有一些输入的表单,我想在数据库中进行一些编辑。我想在数据库中如果有一张图片,以使其不替换为空白。如果输入为空,则从条件分支else echo "Sorry, there was an error uploading your file.";中获取错误。如果我上传图片,一切正常。这是我的代码

<?php

include "../../../config/config.php";
session_start();

if (isset($_GET['car'])) {
    $car = $_GET['car'];
} else {
    die("Not found");
}


if (isset($_POST['submit-edit'])) {



    $title = mysqli_real_escape_string($con, $_POST['title-edit']);
    $description = mysqli_real_escape_string($con, $_POST['description-edit']);
    $category = mysqli_real_escape_string($con, $_POST['category-edit']);



    /* ----------------------- MAIN IMAGE  -------------------------- */
    $target_dir = "../../../img/found/thumbs-category/";
    $target_file2 = "" . basename($_FILES["img-edit"]["name"]);
    $target_file = $target_dir . basename($_FILES["img-edit"]["name"]);

    $uploadOk = 1;
    $imageFileType = pathinfo($target_file, PATHINFO_EXTENSION);

    // Check file size
    if ($_FILES["img-edit"]["size"] > 100000) {
        $_SESSION['image-size'] = 1;

        header("Location: /dashboard/views/edit.php?car=$car");
        exit();
    }
//
    //Allow certain file formats
    if ($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" && $imageFileType != NULL) {
        $_SESSION['image-format'] = 1;

        header("Location: /dashboard/views/edit.php?car=$car");
        exit();
    }

    // Check if $uploadOk is set to 0 by an error
    if ($uploadOk == 0) {

    } else {
        if (move_uploaded_file($_FILES["img-edit"]["tmp_name"], $target_file)) {


        } else {
            echo "Sorry, there was an error uploading your file.";
            exit();
        }


        $query = "UPDATE cars
            SET title='" . $title . "', text='" . $description . "', image='" . $target_file2 . "', fk_cars_first='" . $category . "' WHERE car=" . $car;


        $result = mysqli_query($con, $query);
//                var_dump($query);
//                exit();
        if ($result) {


            header("Location: /dashboard/views/edit.php?car=$car");
        } else {
//
            echo "error";
            exit();
            header("Location: /dashboard/views/edit.php?car=$car");
        }
    }
}
?>


更确切地说,在我的数据库中

标题|描述|图片fk_category
测试更多文字car.jpg调整

当我要编辑数据库时,我使用表单,并且如果type =“ file”的输入为空,我想保留实际路径不抹掉。正确的代码执行类似的操作。和数据库看起来像

标题|描述|图片fk_category
证明| ed!t | | tuning_tex_edited

如果为空,则获取错误Sorry, there was an error uploading your file.,并且在数据库中,路径为空白。

最佳答案

只需使用以下代码:

if ($_FILES['img-edit']){
  foreach($_FILES['img-edit']['name'] as $a=>$v){

    //Check if empty
    if(!empty($_FILES['img-edit']['name'][$a])){

       //Check size of image
       if($_FILES['img-edit']['size'][$a]>0){

         //Now code here

       }
    }
  }
}

关于php - 如果输入图像为空请给我错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39266775/

10-16 14:49