将图像上传到文件夹

时间:2014-01-20 11:31:26

标签: php image upload

我正在制作一个用户可以将图片上传到文件夹的表单。我有这个代码

<?php

$con = mysqli_connect("localhost", "root", "", "portfolio");

$query = null;

$image_name = $_FILES['image']['name'];
$image_type = $_FILES['image']['type'];
$image_size = $_FILES['image']['size'];
$image_tmp_name = $_FILES['image']['tmp_name'];

if ($image_name != '' && ($image_type = "image/jpeg" || $image_type = "image/png" || $image_type = "image/gif"))
    if (move_uploaded_file($image_tmp_name, "project_pics/$image_name"))

        $query = mysql_query("INSERT INTO images (name, photo) VALUES('$image_name','images/$image_name')");

if ($query == true) {
    echo 'Image uploaded';
    echo "<img src='project_pics/$image_name'";
}

else {
    echo 'Please select an image';
    exit();
}

每当我尝试上传图片时,我都会收到来自其他人的回音“请选择图片”

我不知道问题是什么。

提前致谢

编辑:我也试图将图像名称和路径存储在数据库中。忘记提及

3 个答案:

答案 0 :(得分:2)

你不能混合mysqlmysqli(......你可以,但不是你的方式)。

mysql_query(....不能是false,因为没有连接。

您从mysqli_connect()开始。

引用php.net:

  

失败时返回FALSE。对于成功的SELECT, SHOW, DESCRIBE or EXPLAIN次查询,mysqli_query()将返回mysqli_result个对象。对于   其他成功的查询mysqli_query()将返回TRUE

最好是使用davidkonrad的方法或($query !== false)

进行检查

答案 1 :(得分:0)

mysql_query函数返回资源,您正在检查是否为真  

$con = mysqli_connect("localhost", "root", "", "portfolio");

$query = null;

$image_name = $_FILES['image']['name'];
$image_type = $_FILES['image']['type'];
$image_size = $_FILES['image']['size'];
$image_tmp_name = $_FILES['image']['tmp_name'];

if ($image_name != '' && ($image_type = "image/jpeg" || $image_type = "image/png" || $image_type = "image/gif")){
    if (move_uploaded_file($image_tmp_name, "project_pics/$image_name"))
        $query = mysql_query("INSERT INTO images (name, photo) VALUES('$image_name','images/$image_name')") or die(mysql_error());


    echo 'Image uploaded';
    echo "<img src='project_pics/$image_name'";
} else {
    echo 'Please select an image';
    exit();
}

答案 2 :(得分:0)

你需要注意一些事情

  1. 确保。您的表单有enctype="multipart/form-data"

  2. mysql_query更改为mysqli_query

    $query = mysqli_query("INSERT INTO images (name, photo)  
    VALUES('$image_name','images/$image_name')");