使用PHP和MySQL将图像插入db

问题描述 投票:0回答:1

我有一个用户仪表板,我试图在其中允许用户上传自己的个人资料图像。目前,在profile.php页面中,我有一个简单的if语句,该语句表示如果imagePath列下的db内部没有图片,则显示默认缩略图else,并显示用户图像。

以下脚本将正确的映像上载到PC上的物理文件夹中,但没有上载到DB中。如果有人可以清楚地看到没有发生这种情况,请告诉我。

另一个问题是它正在使用我认为的$imageNewName创建新文件名,如果数据库中已经存在相同的图像名,这只会为该图像创建一个新名称?

profile.php:

<div class="grid-2">
    <div class=" profileImage">
     <p><b>Profile Picture: </b>
     <?php 
         $picture = $row['imagePath'];
         if (empty($picture)){
             echo "<img src='profiles/no-image.png' width='100' height='100' >";
         } else {
              echo "<img src='".$row['imagePath']."' width='100' height='100' >";    
         };
     ?>
<form action="scripts/edit-picture.php" method="POST" enctype="multipart/form-data">
    <input type="file" name="image" id="image">
    <button name="edit-picture" type="submit">Upload / Edit Picture</button></p>
</form>
</div>

scripts / edit-picture.php

<?php
    if (isset($_POST['edit-picture'])) {

        require '../header.php';
        $studentID = $_SESSION['studentID'];


        $image = $_FILES['image'];

        $imageName = $_FILES['image']['name'];
        $imageTempName = $_FILES['image']['tmp_name'];
        $imageSize = $_FILES['image']['size'];
        $imageError = $_FILES['image']['error'];
        $imageType = $_FILES['image']['type'];

        $imageExt = explode('.', $imageName);
        $imageRealExt = strtolower(end($imageExt));
        $fileExtAllow = array('jpg', 'jpge', 'png');

        if(in_array($imageRealExt, $fileExtAllow)) {
            if ($imageError === 0 ){
                if($imageSize < 6000000){
                    $imageNewName = uniqid('', true).".".$imageRealExt;
                    $filePath = '../profiles/'.$imageNewName;
                    move_uploaded_file($imageTempName, $filePath);

                    $stmt = $conn->prepare ("INSERT INTO `profileImage` (`imageID`, `imagePath`, `studentID`) VALUES (NULL, ?, ?) ");
                    $stmt->bind_param("si", $filePath, $studentID); 
                    $stmt->execute() or die("Failed to insert image into the database");

                    header("Location: ../profile.php?imageuploaded");
                } else {
                    echo "The file size is too large.";
                }
            } else {
                echo "There was an error with uploading this file.";
            }
        } else {
            echo "You cannot upload this file type, must be a jpg or png type.";
        }
    }
?>
php mysql sql prepared-statement
1个回答
0
投票

我的想法是,您要绑定3个参数,但只能有2个空间。因为bind()语句中有3个,但查询中只有2个问号。根据我的想法,错误日志应该对此有所说明。

© www.soinside.com 2019 - 2024. All rights reserved.