简体   繁体   中英

Folder name becomes value in database when update image using pdo

I tried to update picture in database, but the value in database become like this : user_images/photo.jpg It should be photo.jpg only but why was it followed by folder name? It also made the photo can't be saved in folder.

Here is the editform

<?php 
    $id = $_GET['id'];
    $edit = $db_con->query("SELECT foto FROM mahasiswa WHERE nim='$id'");
    $row = $edit->fetch(PDO::FETCH_ASSOC);
?>
<div class="panel panel-default">
    <!-- Default panel contents -->
    <div class="panel-body">
        <form action="" method="POST" class="form-horizontal" enctype="multipart/form-data" role="form">
                <div class="form-group">
                    <center>
                      <legend>Upload Foto Profil  Mahasiswa </legend>
                    </center>
                </div>

                <div class="form-group">
                    <label for="input" class="col-sm-4 control-label">Pas Foto Mahasiswa :</label>
                  <div class="col-sm-6">
                      <p>
                        <input type="hidden" name="nim" value="<?php echo $id; ?>">
                        <input class="input-group" required="required" type="file" name="foto" accept="image/*" />
                    </p>
            </div>
                </div>


                <div class="form-group">
                    <div class="col-sm-6 col-sm-offset-4">
                        <button type="submit" name="edit_foto" class="btn btn-primary">Update</button>
                        <a href="?apps=ubahmhs" class="btn btn-warning">Batal</a>
                    </div>
                </div>
        </form>
    </div>
</div>

And this is the process

<?php 

if (isset($_POST['edit_foto'])) {
    try{
        $path="user_images/" . basename($_FILES['foto']['name']);
        move_uploaded_file($_FILES['foto']['tmp_name'], $path);
        $edit = $db_con->prepare("UPDATE mahasiswa SET foto=:foto WHERE nim=:nim");
        $edit->bindParam(":nim", $_POST['nim']);
        $edit->bindParam(":foto", $path);
        $edit->execute();
        echo "<script>location.href='?apps=ubahmhs';</script>"; 
        exit();
    } 
        catch (PDOException $e) {
        echo $e->getMessage();
            }
    }
        else {'location=apps/app_ubahmhs/view.php'; }

?>

I need your helping so much. Thanks before for every responses

You are using $path to save image name in database, which contains user_images along with the file name. You should keep file name in separate variable like below:

$imageName = basename($_FILES['foto']['name']);
$path="user_images/" . $imageName;

And then while binding parameters use:

$edit->bindParam(":foto", $imageName);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM