使用php上传图像并将表单数据保存到Mysql数据库中

时间:2016-07-05 09:32:03

标签: php mysql image-uploading

我正在编写一个代码,我可以在文件夹中上传图像并将数据格式保存到Mysql数据库中。目前只在数据库表中保存数据表单正在运行,但我无法将图像上传到文件夹中。这是代码:

    <?php

if(isset($_POST['upload_img'])){

$file_name = $_FILES['image']['name'];
$file_type = $_FILES['image']['type'];      
$file_size = $_FILES['image']['size'];
$file_tmp_name  = $_FILES['image']['tmp_name'];

if($file_name){
            move_uploaded_file($file_tmp_name,"images/$file_name");

            }
}
?>
<?php
  include 'guestconfig/config.php';

if (isset($_POST['upload_img']) && $_POST['upload_img']=="invia")
{
        $image = $file_name;
        $title = addslashes($_POST['title']);
        $price = addslashes($_POST['price']);



  $sql = "INSERT INTO testone
(image,title,price) VALUES ('$image', '$title','$price')";
  if($result = mysql_query($sql) or die (mysql_error()))
  {
    echo "Inserimento avvenuto con successo.<br>
    Vai alla <a href=\"index.php\">Home Amministrazione</a>";
  }
}else{
  ?>
  <table border="1">
  <tr>
  <td>
  <img src="xxx.jpg" alt="xxx" />
  <img src="xxx.jpg" alt="xxx" />
  </td>

  </tr>
  <tr>
  <td>

  <form action="" method="post" enctype="multipart/form-data">

<label>upload image </label><br>
<input type="file" name="image"><br>
<br><br>

title:
<input name="title" type="text"><br><br>

price:
<input name="price" type="text"><br><br>

<input name="upload_img" type="submit" value="invia">
</form>
</td>

</tr>
</table>
  <?php
}
?>
<br>

我希望你能帮助我。谢谢! :)

编辑:好的,现在我可以上传我的图片,但我无法保存图片名称(我可以之前)。我该怎么办呢?谢谢! :)

EDIT2:好的,现在它很完美......感谢大家! :)

3 个答案:

答案 0 :(得分:1)

表格标签必须像这样

 <form action="" method="post" enctype="multipart/form-data">

在php中你可以做这样的事情

if(!empty($file_name)){
              move_uploaded_file($file_tmp_name,"images/".$file_name);
            }

答案 1 :(得分:1)

嗨首先用ctype="multipart/form-data"

替换enctype="multipart/form-data"
   if(!empty($file_name)){
                  if(move_uploaded_file($file_tmp_name,"images/".$file_name))
echo "image uploaded";
else  echo "image not uploaded";


                }

答案 2 :(得分:1)

表单标记中有错误

<form action="" method="post" enctype="multipart/form-data">