обновить, но не удаляет изображение из папки, которую я пробовал в отдельном файле, но не работает - PullRequest
0 голосов
/ 24 мая 2018

`это мой новый файл index.php

<?php
include('db.php');
if(isset($_POST['submit']))
{
    $name = $_POST['name'];

    $image = $_FILES['image']['name'];
    $query = "INSERT INTO `img_table`(`name`, `imgtitle`) 
               VALUES ('$name','$image')";
    header("location:fetch.php");
    if(mysqli_query($con,$query))
    {
        move_uploaded_file($_FILES['image']['tmp_name'],"image/$image");
    }


}

?>
<html>
<head><title>hi</title></head>

<body>
    <form method="POST" enctype="multipart/form-data" >
    <table border=1px;>
        <tr>
        <th>name</th>
        <td><input type="text" name="name" /></td>
        </tr>

        <tr>
        <th>img_title</th>
        <td><input type="file" name="imgtitle"/>
        </tr>

        <tr>
        <input type="submit" name="submit" value="add"/>
        </tr>

    </table>
    </form>
</body>

` это моя страница db.php

<?php
$con = mysqli_connect("localhost" ,"root", "","crud");
if($con){
    echo "connected successfully";
}

?>

this is my index.php page

<?php
include('db.php');
if(isset($_POST['submit']))
{
    $name = $_POST['name'];
    $sname = $_POST['surname'];
    $city = $_POST['city'];
    $state = $_POST['state'];
    $image = $_FILES['image']['name'];
    $query = "INSERT INTO `table`(`name`, `surname`, `city`, `state`, `image`) 
               VALUES ('$name','$sname','$city','$state','$image')";
    header("location:fetch.php");
    if(mysqli_query($con,$query))
    {
        move_uploaded_file($_FILES['image']['tmp_name'],"image/$image");
    }


}

?>



<html>
    <head>
    <title> crud operation </title>
    </head>

    <body>
        <table border=1px; solid;>
        <form method = "POST" action = "" enctype = "multipart/form-data">
            <label> name </label>
            <input type = "text" name = "name"/><br>

            <label> Surname </label>
            <input type = "text" name = "surname"/><br>

            <label> city </label>
            <input type = "text" name = "city"/><br>

            <label> state </label>
            <input type = "text" name = "state"/><br>

            <label> image </image>
            <input type= "file" name = "image"/>

            <tr>
            <td><input type = "submit" name= "submit" value="upload"/></td>
            </tr>

        </form>
        </table>
    </body>

</html>

это мой fetch.php

<?php 
include('db.php');
?>

<html>
<table align = "center" border = 1px; >
    <tr><th>id</th>
        <th>name</th>
        <th>surname</th>
        <th>city</th>
        <th>state</th>
        <th>image</th>
        <th colspan = "2">Action</th>
    </tr>
    <?php
        $query ="SELECT * FROM `table`";

        $fire = mysqli_query($con,$query)or die("could not fetch". mysqli_error($con));

        while($row = mysqli_fetch_array($fire))
        {   
    ?>
        <tr><td><?php echo $row['id'];?></td>
            <td><?php echo $row['name'];?></td>
            <td><?php echo $row['surname'];?></td>
            <td><?php echo $row['city'];?></td>
            <td><?php echo $row['state'];?></td>

            <td><img = src = "image/<?php echo $row['image'];?>" style="width:100px; height:100px;" > </td>
            <td><a href ='update.php? id=<?php echo $row['id']?> &name=<?php echo $row['name']?> &sname=<?php echo $row['surname']?>&city=<?php echo $row['city']?>
                                      &state=<?php echo $row['state']?>
                                      &image=<?php echo $row['image']?>
                                     '/> EDIT </a></td>

            <td> <a href ='delete.php? id=<?php echo $row['id']?>'/>DELETE</a></td> 

        </tr>


    <?php } ?>
        </table>
        </html>

Это моя проблема с страницей update.php - изображение успешно обновляется, но не удаляет старое изображение из папки.

 <?php
        include('db.php');
        if(isset($_POST['UPDATE']))
        {   
        $id = $_REQUEST['id'];
        $name = $_REQUEST['name'];
        $surname = $_REQUEST['sname'];
        $city = $_REQUEST['city'];
        $state = $_REQUEST['state'];
        $image = $_FILES['image']['name'];

        $query = "UPDATE `table` SET `name`='$name' ,`surname`='$surname' ,
                 `city`='$city',`state`='$state',`image`='$image'  WHERE id = '$id' ";
            $fire = mysqli_query($con,$query);

            move_uploaded_file($_FILES['image']['tmp_name'],"image/$image");
            unlink('image/$image');
            header('location:fetch.php');

        }
        ?>

         <html>
            <head>
            <title> crud operation </title>
            </head>

            <body>
                <table  border=1px:solid;>
                <form  method = "POST" action = "#" enctype = "multipart/form-data">
                    <label> name </label>
                    <input type = "text" name = "name" value = <?php echo "$_REQUEST[name]";?> /> <br>

                    <label> Surname </label>
                    <input type = "text" name = "surname" value = <?php echo "$_REQUEST[sname]";?> /><br>

                    <label> city </label>
                    <input type = "text" name = "city" value= <?php echo "$_REQUEST[city]";?> /><br>

                    <label> state </label>
                    <input type = "text" name = "state" value= <?php echo "$_REQUEST[state]";?> /><br>

                    <label> image </image>
                    <input type= "file" name = "image" value= <?php echo "$_REQUEST[image]";?> /><br>

                    <tr>
                    <td><input type = "submit" name= "UPDATE" value="UPDATE"/></td>
                    </tr>

                </form>
                </table>
            </body>

        </html>

Я хочу удалить староеизображение из папки, когда я обновляю любое изображение из таблицы.но этот код только обновляет файл в базе данных, а также сохраняет новое изображение в папке, но не удаляет старое изображение из папки, так как я новичок, и здесь я знаю, что есть эксперты, которые помогают мне понять, что не так с моим моим кодом, и предлагают некоторые лучшие коды,Пожалуйста, помогите и спасибо заранее.

1 Ответ

0 голосов
/ 04 июня 2018

Проверьте код ниже, где я обновил некоторый код, особенно у меня есть новое, добавить скрытое поле старого изображения, а затем получить это значение и удалить одно условие изображения, загруженного во время редактирования или нет.Также, пожалуйста, измените таблицу в запросе, потому что мы не можем использовать имя таблицы table, потому что это зарезервированное ключевое слово.

<?php
    include('db.php');
    if(isset($_POST['UPDATE']))
    {   
    $id = $_REQUEST['id'];
    $name = $_REQUEST['name'];
    $surname = $_REQUEST['sname'];
    $city = $_REQUEST['city'];
    $state = $_REQUEST['state'];

    print_r($_FILES);
    //check new image is upload
    if(isset($_FILES['image']['name']) && $_FILES['image']['name'] != '' ){

        $image = $_FILES['image']['name'];
        move_uploaded_file($_FILES['image']['tmp_name'],"image/$image");
        unlink('image/'.$_POST['old_image']);
    }
    else{
        $image = $_POST['old_image'];
    }

    $query = "UPDATE `user` SET `name`='$name' ,`surname`='$surname' ,
             `city`='$city',`state`='$state',`image`='$image'  WHERE id = '$id' ";
        $fire = mysqli_query($con,$query);

        header('location:fetch.php');

    }
    ?>

     <html>
        <head>
        <title> crud operation </title>
        </head>

        <body>
            <table  border=1px:solid;>
            <form  method = "POST" action = "#" enctype = "multipart/form-data">
                <label> name </label>
                <input type = "text" name = "name" value = <?php echo "$_REQUEST[name]";?> /> <br>

                <label> Surname </label>
                <input type = "text" name = "surname" value = <?php echo "$_REQUEST[sname]";?> /><br>

                <label> city </label>
                <input type = "text" name = "city" value= <?php echo "$_REQUEST[city]";?> /><br>

                <label> state </label>
                <input type = "text" name = "state" value= <?php echo "$_REQUEST[state]";?> /><br>

                <label> image </image>
                <input type= "hidden" name = "old_image" value= <?php echo "$_REQUEST[image]";?> /><br>        
                <input type= "file" name = "image"  /><br>

                <tr>
                <td><input type = "submit" name= "UPDATE" value="UPDATE"/></td>
                </tr>

            </form>
            </table>
        </body>

    </html>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...