php - 无法使用 php 将图像上传和存储到数据库

标签 php mysql image file-upload upload

我尝试用php建立一个上传图片系统。测试后,系统回显“图片已上传”,但它没有显示在数据库中。这是我的代码

上传.php

<?php
//connect database
include('config.php');

//file properties
 if(isset($_FILES['image'])){
   $file = $_FILES['image']['tmp_name'];
}

if(!isset($file)){
    echo "Please select an image";
}
else{
    $image = addslashes(file_get_contents($_FILES['image']['tmp_name']));
    $image_name =addslashes($_FILES['image']['name']);
    $image_size =getimagesize($_FILES['image']['tmp_name']);

    if ($image_size == FALSE) {
        echo "This is not an image";
    }
    else{
        $insert = "INSERT INTO image(name,picture) VALUES ('$image_name','$image')";

        if(!$insert){
            echo "Problem uploading";
        }
        else {
            $lastid =mysqli_insert_id($con);
            echo "Image Uploaded <p />Your Image :<p /><img src=get.php?id=$lastid>";
        }
    }
}


?>

获取.php

<?php
include ('config.php');

$id = addslashes($_REQUEST['id']);

$image = mysqli_query($con ,"SELECT * FROM image WHERE id=$id");
$image = mysqli_fetch_assoc($image);
$image = $image['picture'];

header("Content-type :image/jpeg");
?>

我点击提交按钮而不选择任何文件,这 2 行警告出现了

Warning: file_get_contents(): Filename cannot be empty in upload.php line 14.

line14 is this $image = addslashes(file_get_contents($_FILES['image']['tmp_name']));

Warning: getimagesize(): Filename cannot be empty in in upload.php line 16.

while line 16 is this $image = addslashes(file_get_contents($_FILES['image']['tmp_name']));

对此有什么想法吗?

最佳答案

您需要一个函数来发送您的查询,否则您只需填写一个字符串:this:

$insert = "INSERT INTO image(name,picture) VALUES ('$image_name','$image')";

后面应该跟这个:

mysqli_query($con, $insert);

这些警告是由您的代码的多个问题引起的。首先你在检查文件是否以错误的方式上传:this

if(isset($_FILES['image'])){
    $file = $_FILES['image']['tmp_name'];
}

将始终设置一个 $file 变量,即使没有文件被选择到表单中,因此永远不会执行这个 if 语句:

if(!isset($file)){
    echo "Please select an image";
}

并且始终执行 else block 中的内容,这会导致错误,因为您提到的包含在 else block 中的函数无法对任何文件进行操作。

因此,只需正确检查文件上传即可解决问题:一种方法是先删除它,这是无用的

if(isset($_FILES['image'])){
    $file = $_FILES['image']['tmp_name'];
}

然后改变这个:

if(!isset($file)){
    echo "Please select an image";
}

为此:

if(!isset($_FILES['image']['tmp_name'])){
    echo "Please select an image";
}

关于php - 无法使用 php 将图像上传和存储到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27591379/

相关文章:

javascript - 如何在核心php项目中使用yii框架项目的母版页?

php - 如何使用 HTML 将菜单文件包含并链接到每个网页?

mysql - MySQL CASE/WHEN 的替代方案?

php - $data=mysqli_fetch_array($result) 不起作用

html - 用三 Angular 形创建透明的CSS边框

java - 如何制作 Jbutton 图像数组

image - 是否可以编辑 "ionic-img-viewer"npm 或复制 Ionic 2 中的图像样式?

php - "Indirect modification of overloaded element of SplFixedArray has no effect"

php - Carbon laravel 添加到文件名

mysql - 插入到哪里问题(将值添加到新行)