简体   繁体   English

如何将上传的图像保存在数据库中

[英]How to save uploaded image in database

I need help in writing this code to upload and save uploaded image in data base.我需要帮助编写此代码以在数据库中上传和保存上传的图像。

File 1:文件 1:

<?php

      <form action="upload.php" method="post" enctype="multipart/form-data" target="upload_target" onsubmit="startUpload();" >
                     
                <label>File:  
                <input name="myfile" type="file" size="30" />
                </label>
                       
                <input type="submit" name="submitBtn" class="sbtn" value="Upload" />
                       
                     
                  <iframeid="upload_target"name="upload_target"src="#"style="width:0;height:0;border:0px solid #fff;"></iframe>
                </form>
                </div>

File 2:文件2:

<?php




   // Edit upload location here
   $destination_path = getcwd().DIRECTORY_SEPARATOR;
   $target_path="my/";
   $result = 0;
   $name=$_FILES['myfile']['name'];
   $target_path = $target_path . basename( $_FILES['myfile']['name']);

   if(@move_uploaded_file($_FILES['myfile']['tmp_name'], $target_path)) {
   list($width, $height, $type, $attr) = getimagesize($target_path);
echo "Image width " .$width;
echo "<BR>";
echo "Image height " .$height;
echo "<BR>";
echo "Image type " .$type;
echo "<BR>";
echo "Attribute " .$attr;
        

      $result = 1;
   }
   
  // sleep(1);
   
   

   
$link=mysql_connect('localhost','root','');
if(!$link)
{die('you cannot connect to database...');}
$db=mysql_select_db('final');
if(!$db)die('smile');

if (isset($_FILES['myfile']) && $_FILES['myfile']['size'] > 0) {

// define the posted file into variables 
$name = $_FILES['myfile']['name']; 
$tmp_name = $_FILES['myfile']['tmp_name']; 
$type = $_FILES['myfile']['type']; 
$size = $_FILES['myfile']['size']; 

// if your server has magic quotes turned off, add slashes manually 
//if(!get_magic_quotes_gpc()){ 
//$name = addslashes($name); 
//} 

// open up the file and extract the data/content from it 
$extract = fopen($tmp_name, 'r'); 
$content = fread($extract, filesize($tmp_name)); 
$content = addslashes($content); 
fclose($extract);  

// connect to the database 


// the query that will add this to the database 
$s=mysql_query("SET NAMES 'utf8'");
$sql = "INSERT INTO `final`.`products` (`Productcode`, `Productname`, `Price`,`Descriptionofgood`, `image`) VALUES ('','','','','".$target_path."') WHERE `products`.`Productcode`='1371' ";
$results = mysql_query($sql);
if(!$result)die('not');
}

?>

Technically, if it is a small project.从技术上讲,如果它是一个小项目。 You should not store images files in "Database" ;您不应将图像文件存储在“数据库”中; rather only their link (you may not even need that).而只是他们的链接(您甚至可能不需要那个)。 Image or any media files are stored on server along with your other files (html,css,php).图像或任何媒体文件与您的其他文件(html、css、php)一起存储在服务器上。 Of course, you need to put them on a dedicated folder for it.当然,您需要将它们放在专门的文件夹中。 The reason for not storing on database : because they are meant for data retrieval only and more importantly they are of smaller size (bigger sizes do exist, i am speaking in case of a small project which requires least possible resources. Storing media files on database is just not efficient.不存储在数据库上的原因:因为它们仅用于数据检索,更重要的是它们的尺寸较小(确实存在较大的尺寸,我说的是一个需要最少资源的小项目。将媒体文件存储在数据库上只是效率不高。

Looking at your code, i can tell you are trying to store the files on your server.查看您的代码,我可以告诉您正在尝试将文件存储在您的服务器上。

They have used a very simple script for uploading here .他们使用了一个非常简单的脚本来上传这里 Try it on your localhost before trying on a server.在尝试服务器之前先在本地主机上尝试。

if(@move_uploaded_file($_FILES['myfile']['tmp_name'], $target_path)) is incorrect. if(@move_uploaded_file($_FILES['myfile']['tmp_name'], $target_path))不正确。

It should be if(move_uploaded_file($_FILES['myfile']['tmp_name'], $target_path))应该是if(move_uploaded_file($_FILES['myfile']['tmp_name'], $target_path))

Remove the @ .删除@

I have created three page for it我为它创建了三个页面

  1. index.php (Form for uplad image) index.php(上传图片的表格)

  2. upload.php (Save the image in upload folder and its path in database) upload.php(将图片保存在上传文件夹中,并保存在数据库中的路径)

3.showimage.php (Show the images from database) 3.showimage.php (显示数据库中的图片)

Database Structure数据库结构

id int(4) auto increment - image varchar(100) - image_name varchar(50) id int(4) 自动递增 - 图像 varchar(100) - image_name varchar(50)

here is the code:这是代码:

index.php索引.php

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

<label>Choose File to Upload:</label><br />

<input type="hidden" name="id" />

<input type="file" name="uploadimage" /><br />

<input type="submit" value="upload" />

</form>

uplad.php上传文件

<?php
$target_Folder = "upload/";

$uid = $_POST['id'];

$target_Path = $target_Folder.basename( $_FILES['uploadimage']['name'] );

$savepath = $target_Path.basename( $_FILES['uploadimage']['name'] );

    $file_name = $_FILES['uploadimage']['name'];

    if(file_exists('upload/'.$file_name))
{
    echo "That File Already Exisit";
    }
    else
    {

        // Database 
    con=mysqli_connect("localhost","user_name","password","database_name"); //Change it if required

//Check Connection
        if(mysqli_connect_errno())
        {
            echo "Failed to connect to database" .     mysqli_connect_errno();
        }

        $sql = "INSERT INTO image (id,image, image_name)
                    VALUES     ('','$target_Folder$file_name','$file_name') ";

        if (!mysqli_query($con,$sql))
        {
            die('Error: ' . mysqli_error($con));
        }
        echo "1 record added successfully in the database";
        echo '<br />';
        mysqli_close($con);

        // Move the file into UPLOAD folder

        move_uploaded_file( $_FILES['uploadimage']['tmp_name'],     $target_Path );

        echo "File Uploaded <br />";
        echo 'File Successfully Uploaded to:&nbsp;' . $target_Path;
        echo '<br />';  
        echo 'File Name:&nbsp;' . $_FILES['uploadimage']['name'];
        echo'<br />';
        echo 'File Type:&nbsp;' . $_FILES['uploadimage']['type'];
        echo'<br />';
        echo 'File Size:&nbsp;' . $_FILES['uploadimage']['size'];

    }
?>

<a href="showimage.php">Show Image</a>

showimage.php显示图像.php

<?php


$con=mysqli_connect("localhost","user_name","password","test"); //Change it if required

// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$result = mysqli_query($con,"SELECT * FROM image " );


while($row = mysqli_fetch_array($result))
{
echo '<img src="' . $row['image'] . '" width="200" />';
echo'<br /><br />';  
}


mysqli_close($con);

?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM