如果输入为空,则保留图像的路径

时间:2016-09-01 07:02:55

标签: php sql

我有一个表单,其中包含一些输入,我希望在数据库中进行一些编辑。我想在数据库中存在一张图片,以防止它被空格替换。 这是我的代码

<?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");
        }
    }
}
?>

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

title | description | image  |  fk_category
test    more text     car.jpg   tuning

当我想编辑数据库时,我使用表单,如果type =“file”的输入为空,我想保持实际路径不要擦除..正确的代码做这样的事情..我设置提交按钮和数据库看起来像

title      | description | image  |  fk_category
testedited |   ed!t      |        |  tuning_tex_edited

1 个答案:

答案 0 :(得分:0)

您可以修改查询以仅在需要时更新图像:

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

if(!empty($target_file2)){
    $query .= ", image='" . $target_file2 . "'";
}

$query .= " WHERE car=" . $car;