Image使用PHP上传到mysql数据库

时间:2014-09-26 09:56:43

标签: php mysql

我试图将图片上传到mysql表。选择图像时,它工作正常。但是如果没有选择图像,它会显示错误信息。我该如何解决?

  

警告:file_get_contents():文件名不能为空   第23行的C:\ wamp \ www \ firstdialnew \ firstdial \ adhandler.php

$stype=$_POST['stype'];
$image = addslashes(file_get_contents($_FILES['image']['tmp_name']));
$image_name = addslashes($_FILES['image']['name']);

if($stype="")
{
echo "Please fill all the details";
}else{
$sql=mysql_query("INSERT INTO ads
                            (sid,stype,image,image_name)
                            VALUES(NULL,'$stype','$image','$image_name')");
echo "Details Successfully send";
}

5 个答案:

答案 0 :(得分:3)

您需要检查/验证图片是否上传或不尝试类似的内容

if (!empty($_FILES['image']['name'])) {
   $image = addslashes(file_get_contents($_FILES['image']['tmp_name']));
   $image_name = addslashes($_FILES['image']['name']);
}else{
   $image = '';
   $image_name = '';
}

答案 1 :(得分:1)

您没有检查$_FILES尝试此

$stype=$_POST['stype'];
if(isset($_FILES['image']) ) {
    $image = addslashes(file_get_contents($_FILES['image']['tmp_name']));
    $image_name = addslashes($_FILES['image']['name']);
}else{
    $image = '';
    $image_name = '';
}

我建议您将文件上传到文件夹中,并将文件名存储在mysql表中。

以下是您可以这样做的方法

$file_path = "uploads/";

if(isset($_FILES['image']) ) {
   $file_name  = basename( $_FILES['uploaded_file']['name']);
   $file_path = $file_path . $file_name;

   //You should validate the image before upload
   move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path);
 }else{
    $image = '';
    $image_name = '';
}

//now store file name in db
$sql=mysql_query("INSERT INTO ads
                        (sid,stype,image,image_name)
                        VALUES(NULL,'$stype','$file_name','$image_name')");

答案 2 :(得分:1)

根据我的经验,您应该将图像保存到文件夹中(例如:public / upload / images / image_name.png) 并将图像路径保存到数据库中。 这很简单,数据库的大小也不大

答案 3 :(得分:0)

你添加了:

    <form method="POST" enctype="multipart/form-data">

进入您的表单(enctype =&#34; multipart / form-data&#34;)

答案 4 :(得分:0)

试试这个:

 $stype=$_POST['stype'];
     $image_name ='';
     $image='';
     if(!empty($_FILES['image'])) {
     $image = addslashes(file_get_contents($_FILES['image']['tmp_name']));
     $image_name = addslashes($_FILES['image']['name']);
      } 
      if($stype="")
      {
      echo "Please fill all the details";
      }else{
       $sql=mysql_query("INSERT INTO ads
                        (sid,stype,image,image_name)
                        VALUES(NULL,'$stype','$image','$image_name')");
         echo "Details Successfully send";
       }