简体   繁体   中英

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:

<?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:

<?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). 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.

It should be 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)

  2. upload.php (Save the image in upload folder and its path in database)

3.showimage.php (Show the images from database)

Database Structure

id int(4) auto increment - image varchar(100) - image_name varchar(50)

here is the code:

index.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


$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);

?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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