使用PHP和MySQL将图像文件上传和存储在数据库中,并附带说明

时间:2019-07-06 12:16:34

标签: php image-uploading

我一直在尝试将图像上传到带有图像描述的日期数据库,然后从数据库中获取数据,然后将描述文件添加到图像中。我是php的新手,我找不到互联网信息,我已将其上传到数据库并显示我只是无法获得descriptiono的工作感谢您的帮助

index.php

    <form action="upload.php" method="post" enctype="multipart/form-data">
    Select Image File to Upload:
    <input type="file" name="file">
    <br><input type="text" name="description" placeholder="description of        your image"> 
    <input type="submit" name="submit" value="Upload">
</form>

upload.php

    // Create database connection
    $db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);

    // Check connection
    if ($db->connect_error) {
        die("Connection failed: " . $db->connect_error);
    }
    $statusMsg = '';

    // File upload path
    $targetDir = "upload/";
    $fileName = basename($_FILES["file"]["name"]);
    $targetFilePath = $targetDir . $fileName;
    $fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);

    if(isset($_POST["submit"]) && !empty($_FILES["file"]["name"])){
        // Allow certain file formats
        $allowTypes = array('jpg','png','jpeg','gif','pdf');
        if(in_array($fileType, $allowTypes)){
            // Upload file to server
            if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)){
                // Insert image file name into database
                $insert = $db->query("INSERT into images (file_name, uploaded_on) VALUES ('".$fileName."', NOW())");
                if($insert){
                    $statusMsg = "The file ".$fileName. " has been uploaded successfully.";
                }else{
                    $statusMsg = "File upload failed, please try again.";
                }
            }else{
                $statusMsg = "Sorry, there was an error uploading your file.";
            }
        }else{
            $statusMsg = 'Sorry, only JPG, JPEG, PNG, GIF, & PDF files are allowed to upload.';
        }
    }else{
        $statusMsg = 'Please select a file to upload.';
    }

    // Display status message
    echo $statusMsg;
    ?>

1 个答案:

答案 0 :(得分:0)

您的代码未将description保存到数据库。这就是为什么您不能显示它。

首先,您需要在表description内添加新列images

此后,您必须像使用$fileName

一样获得请求中发送的描述。
$description = $_POST['description'];

您现在可以插入images

$insert = $db->query("INSERT INTO images (file_name, description, uploaded_on) VALUES ('".$fileName."', '".$description."', NOW())");