How to store images in mysql database using php - php

How can i store and display the images in a MySQL database. Till now i have only written the code to get the images from the user and store them in a folder, the code that i wrote till now is:
HTML FILE
<input type="file" name="imageUpload" id="imageUpload">
PHP FILE
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["imageUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
if (move_uploaded_file($_FILES["imageUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["imageUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";}

I found the answer, For those who are looking for the same thing here is how I did it.
You should not consider uploading images to the database instead you can store the name of the uploaded file in your database and then retrieve the file name and use it where ever you want to display the image.
HTML CODE
<input type="file" name="imageUpload" id="imageUpload">
PHP CODE
if(isset($_POST['submit'])) {
//Process the image that is uploaded by the user
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["imageUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
if (move_uploaded_file($_FILES["imageUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["imageUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
$image=basename( $_FILES["imageUpload"]["name"],".jpg"); // used to store the filename in a variable
//storind the data in your database
$query= "INSERT INTO items VALUES ('$id','$title','$description','$price','$value','$contact','$image')";
mysql_query($query);
require('heading.php');
echo "Your add has been submited, you will be redirected to your account page in 3 seconds....";
header( "Refresh:3; url=account.php", true, 303);
}
CODE TO DISPLAY THE IMAGE
while($row = mysql_fetch_row($result)) {
echo "<tr>";
echo "<td><img src='uploads/$row[6].jpg' height='150px' width='300px'></td>";
echo "</tr>\n";
}

if(isset($_POST['form1']))
{
try
{
$user=$_POST['username'];
$pass=$_POST['password'];
$email=$_POST['email'];
$roll=$_POST['roll'];
$class=$_POST['class'];
if(empty($user)) throw new Exception("Name can not empty");
if(empty($pass)) throw new Exception("Password can not empty");
if(empty($email)) throw new Exception("Email can not empty");
if(empty($roll)) throw new Exception("Roll can not empty");
if(empty($class)) throw new Exception("Class can not empty");
$statement=$db->prepare("show table status like 'tbl_std_info'");
$statement->execute();
$result=$statement->fetchAll();
foreach($result as $row)
$new_id=$row[10];
$up_file=$_FILES["image"]["name"];
$file_basename=substr($up_file, 0 , strripos($up_file, "."));
$file_ext=substr($up_file, strripos($up_file, "."));
$f1="$new_id".$file_ext;
if(($file_ext!=".png")&&($file_ext!=".jpg")&&($file_ext!=".jpeg")&&($file_ext!=".gif"))
{
throw new Exception("Only jpg, png, jpeg or gif Logo are allow to upload / Empty Logo Field");
}
move_uploaded_file($_FILES["image"]["tmp_name"],"../std_photo/".$f1);
$statement=$db->prepare("insert into tbl_std_info (username,image,password,email,roll,class) value (?,?,?,?,?,?)");
$statement->execute(array($user,$f1,$pass,$email,$roll,$class));
$success="Registration Successfully Completed";
echo $success;
}
catch(Exception $e)
{
$msg=$e->getMessage();
}
}

insert image zh
-while we insert image in database using insert query
$Image = $_FILES['Image']['name'];
if(!$Image)
{
$Image="";
}
else
{
$file_path = 'upload/';
$file_path = $file_path . basename( $_FILES['Image']['name']);
if(move_uploaded_file($_FILES['Image']['tmp_name'], $file_path))
{
}
}

<!--
//THIS PROGRAM WILL UPLOAD IMAGE AND WILL RETRIVE FROM DATABASE. UNSING BLOB
(IF YOU HAVE ANY QUERY CONTACT:rahulpatel541#gmail.com)
CREATE TABLE `images` (
`id` int(100) NOT NULL AUTO_INCREMENT,
`name` varchar(100) NOT NULL,
`image` longblob NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB ;
-->
<!-- this form is user to store images-->
<form action="index.php" method="post" enctype="multipart/form-data">
Enter the Image Name:<input type="text" name="image_name" id="" /><br />
<input name="image" id="image" accept="image/JPEG" type="file"><br /><br />
<input type="submit" value="submit" name="submit" />
</form>
<br /><br />
<!-- this form is user to display all the images-->
<form action="index.php" method="post" enctype="multipart/form-data">
Retrive all the images:
<input type="submit" value="submit" name="retrive" />
</form>
<?php
//THIS IS INDEX.PHP PAGE
//connect to database.db name is images
mysql_connect("", "", "") OR DIE (mysql_error());
mysql_select_db ("") OR DIE ("Unable to select db".mysql_error());
//to retrive send the page to another page
if(isset($_POST['retrive']))
{
header("location:search.php");
}
//to upload
if(isset($_POST['submit']))
{
if(isset($_FILES['image'])) {
$name=$_POST['image_name'];
$email=$_POST['mail'];
$fp=addslashes(file_get_contents($_FILES['image']['tmp_name'])); //will store the image to fp
}
// our sql query
$sql = "INSERT INTO images VALUES('null', '{$name}','{$fp}');";
mysql_query($sql) or die("Error in Query insert: " . mysql_error());
}
?>
<?php
//SEARCH.PHP PAGE
//connect to database.db name = images
mysql_connect("localhost", "root", "") OR DIE (mysql_error());
mysql_select_db ("image") OR DIE ("Unable to select db".mysql_error());
//display all the image present in the database
$msg="";
$sql="select * from images";
if(mysql_query($sql))
{
$res=mysql_query($sql);
while($row=mysql_fetch_array($res))
{
$id=$row['id'];
$name=$row['name'];
$image=$row['image'];
$msg.= '<img src="data:image/jpeg;base64,'.base64_encode($row['image']). ' " /> ';
}
}
else
$msg.="Query failed";
?>
<div>
<?php
echo $msg;
?>

Related

PHP / MySQL: Image successfully save to database but failed to display at web page

I have a very weird problem in my system. I already create a system to upload the image to the database and display it. The problem is, the image is successfully uploaded but, it will return the message "Failed to upload!". Then, the picture that had been uploaded does not display. Below is my code:
<body>
<div class="wrapperDiv">
<form action="" method="post" id="form" enctype="multipart/form-data">
Upload image :
<input type="file" name="uploadFile" value="" />
<input type="submit" name="submitBtn" value="Upload" />
</form>
<?php
$last_insert_id = null;
include('db2.php');
if(isset($_POST['submitBtn']) && !empty($_POST['submitBtn'])) {
if(isset($_FILES['uploadFile']['name']) && !empty($_FILES['uploadFile']['name'])) {
//Allowed file type
$allowed_extensions = array("jpg","jpeg","png","gif");
//File extension
$ext = strtolower(pathinfo($_FILES['uploadFile']['name'], PATHINFO_EXTENSION));
//Check extension
if(in_array($ext, $allowed_extensions)) {
//Convert image to base64
$encoded_image = base64_encode(file_get_contents($_FILES['uploadFile']['tmp_name']));
$encoded_image = $encoded_image;
$query = "INSERT INTO tbl_images SET encoded_image = '".$encoded_image."'";
$sql = $conn->prepare($query);
$sql -> execute();
//$results = $sql -> fetchAll(PDO::FETCH_OBJ);
echo "File name : " . $_FILES['uploadFile']['name'];
echo "<br>";
if($sql->rowCount() > 1 ) {
echo "Status : Uploaded";
$last_insert_id = $conn-> lastInsertId();
} else {
echo "Status : Failed to upload!";
}
} else {
echo "File not allowed";
}
}
if($last_insert_id) {
$query = "SELECT encoded_image FROM tbl_images WHERE id= ". $last_insert_id;
$sql = $conn->prepare($query);
$sql -> execute();
if($sql->rowCount($sql) == 1 ) {
//$row = mysqli_fetch_object($result);
while($row = $sql->fetch(PDO::FETCH_ASSOC)) {
echo "<br><br>";
echo '<img src="'.$row->encoded_image.'" width="250">';
}
}
}
}
?>
</div>
</body>
Can someone help me? Thanks!
you doing some thing wrong first you encoded the image when store in database so you must decode it again, and the src in tag get a url not image content just echo the content like this:
header('Content-type: image/jpeg');
echo base64_decode($row->encoded_image);
or
<img src="data:image/png;base64,'.$row->encoded_image.'" width="250">
but at all, store images in database is not a good option, your database become too heavy and can't respond fast and get too memory you can just store the image name in database and move the file form special place in your server the you can show like this.
echo '<img src="specialRoot/'.$row->image_name.'" width="250">';
Store images in folder..
I have created uploads folder in root, you can create folder at anywhere and write your path while fetching the image..
<body>
<div class="wrapperDiv">
<form action="" method="post" id="form" enctype="multipart/form-data">
Upload image :
<input type="file" name="uploadFile" value="" />
<input type="submit" name="submitBtn" value="Upload" />
</form>
<?php
$last_insert_id = null;
include('db2.php');
if(isset($_POST['submitBtn']) && !empty($_POST['submitBtn'])) {
if(isset($_FILES['uploadFile']['name']) && !empty($_FILES['uploadFile']['name'])) {
//Allowed file type
$allowed_extensions = array("jpg","jpeg","png","gif");
$name = $_FILES['uploadFile']['name'];
$target_dir = "uploads/"; //give path of your folder where images are stored.
$target_file = $target_dir . basename($_FILES["uploadFile"]["name"]);
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
//Check extension
if( in_array($imageFileType,$allowed_extensions) ){
//Convert image to base64
$image_base64 = base64_encode(file_get_contents($_FILES['uploadFile']['tmp_name']) );
$encoded_image = 'data:image/'.$imageFileType.';base64,'.$image_base64;
//$encoded_image = base64_encode($_FILES['uploadFile']['tmp_name']);
//$encoded_image = $encoded_image;
$query = "INSERT INTO tbl_images SET encoded_image = '".$encoded_image."'";
$sql = $conn->prepare($query);
$result = $sql -> execute();
move_uploaded_file($_FILES['uploadFile']['tmp_name'],$target_dir.$name);
echo "File name : " . $_FILES['uploadFile']['name'];
echo "<br>";
if($result == 1) {
echo "Status : Uploaded";
$last_insert_id = $conn->insert_id;
} else {
echo "Status : Failed to upload!";
}
} else {
echo "File not allowed";
}
}
if($last_insert_id) {
$query = "SELECT encoded_image FROM tbl_images WHERE id= ". $last_insert_id;
$result = $conn->query($query);
while($row = $result->fetch_assoc()){
echo '<img src="'.$row['encoded_image'].'" width="250">';
}
}
}
?>
</div>
</body>

php upload images and save file name to mysql

I have this html form
<form action="insert.php" method="post" enctype="multipart/form-data">>
<p>
<label for="covername">Cover Artwork:</label>
<input type="file" name="file"/>
</p>
<p>
<label for="textname">Text Artwork:</label>
<input type="file" name="textname"/><br><br>
</p>
<input type="submit" name="submit" value="Upload"/>
and this is the insert.php
//Upload cover artwork
$name= $_FILES['file']['name'];
$tmp_name= $_FILES['file']['tmp_name'];
$submitbutton= $_POST['submit'];
$position= strpos($name, ".");
$fileextension= substr($name, $position + 1);
$fileextension= strtolower($fileextension);
if (isset($name)) {
$path= 'uploads/';
if (!empty($name)){
if (move_uploaded_file($tmp_name, $path.$name)) {
echo 'Uploaded!';
}
}
}
//Upload text artwork
$textname= $_FILES['file']['textname'];
$tmp_textname= $_FILES['file']['tmp_textname'];
$textsubmitbutton= $_POST['submit'];
$textposition= strpos($textname, ".");
$textfileextension= substr($textname, $textposition + 1);
$textfileextension= strtolower($textfileextension);
if (isset($textname)) {
$textpath= 'uploads/';
if (!empty($textname)){
if (move_uploaded_file($tmp_textname, $textpath.$textname)) {
echo 'Uploaded!';
}
}
}
// attempt insert query execution
$sql = "INSERT INTO table (covername, textname) VALUES ('$name', '$textname')";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
?>
The covername is saved to the database and the file is uploaded to uploads/ - this works great. But the second upload isn't working at all, textname isn't saved to the db nor is it uploaded. What am i missing?
Just change this:
//Upload text artwork
$textname= $_FILES['textname']['name'];
$tmp_textname= $_FILES['textname']['tmp_name'];
$textsubmitbutton= $_POST['submit'];
$textposition= strpos($textname, ".");
$textfileextension= substr($textname, $textposition + 1);
$textfileextension= strtolower($textfileextension);
if (isset($textname)) {
$textpath= 'uploads/';
if (!empty($textname)){
if (move_uploaded_file($tmp_textname, $textpath.$textname)) {
echo 'Uploaded!';

How to store image link in database php/mysql

I'm trying to allow an admin upload pictures of products in to the database, but I only want to store the link/url of the picture in the database and then store the uploaded file in a folder.
This is what I've got so far, and I keep getting "Sorry there was a problem uploading your file".
Here is the PHP code:
if ($_FILES['product_image']['error'] == 0) { // checking the file for any errors
$imgName = mysql_real_escape_string($_FILES['product_image']['name']); //returns the name of the image and stores it in variable $imgName
$imgData = mysql_real_escape_string(file_get_contents($_FILES["product_image"]["tmp_name"])); // returns the content of the file and stores it in $imgData
$imgType = mysql_real_escape_string($_FILES["product_image"]["type"]); //returns image/whatever the image type is
$targetFolder = "ProductImages/"; //directory where images will be stored...
$targetFolder = $targetFolder . basename($imgName); //adds the image name to the directory
}
$sql = "INSERT INTO products " . "(product_name,product_model,product_price,product_width,product_height,product_weight,product_quantity,product_category,product_subcategory, product_image, product_description,date_added) " . "VALUES('$product_name','$product_model','$product_price','$product_width','$product_height','$product_weight','$product_quantity', '$product_category', '$product_subcategory', '$imgName', '$product_description', NOW())";
//echo $sql;
mysql_select_db('online_store');
$result = mysql_query($sql, $conn);
$itemResult = "";
if (!$result) {
die('Could not enter data: ' . mysql_error());
}
$itemResult = "Product has been added";
if (move_uploaded_file($imgData, "$targetFolder" . $imgName)) { // writes/stores the image in the targetfolder->ProductImages
echo "The file " . basename($imgName) . "has been uploaded!";
} else {
echo "Sorry, there was a problem uploading your file!";
}
and the HTML form:
<form id="product_form" name="product_form" enctype="multipart/form-data" action="inventory_list.php" method="post">
<label for="product_image">Product Image*:</label> <input type="file" name="product_image"id="product_image"/>
</div>
<div>
<button name="add" id="add">Add Item</button>
</div>
</form
Use Sql Query Below.
$sql = "INSERT INTO products(`product_name`,`product_model`,`product_price`,`product_width`,`product_height`,`product_weight`,`product_quantity`,`product_category`,`product_subcategory`,`product_image`,`product_description`,`date_added`) VALUES('".$product_name."','".$product_model."','".$product_price."','".$product_width."','".$product_height."','".$product_weight."','".$product_quantity."', '".$product_category."', '".$product_subcategory."', '".$imgName."', '".$product_description."','".date("Y-m-d H:i:s")."')";
Also Change below line for upload image $imgData = mysql_real_escape_string(file_get_contents($_FILES["product_image"]["tmp_name"])); to $imgData = $_FILES["product_image"]["tmp_name"];
Try this Hope this helps.Not tested
<form id="product_form" name="product_form" enctype="multipart/form-data" method="post" action="" >
<label for="product_image">Product Image*:</label> <input type="file" name="product_image" id="product_image" />
</div>
<div>
<button name="add" id="add">Add Item</button>
</div>
</form>
PHP code :
<?php
if ($_FILES['product_image']['error'] == 0) { // checking the file for any errors
$imgName = mysql_real_escape_string($_FILES['product_image']['name']); //returns the name of the image and stores it in variable $imgName
$imgData = mysql_real_escape_string(file_get_contents($_FILES["product_image"]["tmp_name"])); // returns the content of the file and stores it in $imgData
$imgType = mysql_real_escape_string($_FILES["product_image"]["type"]); //returns image/whatever the image type is
$targetFolder = "ProductImages/"; //directory where images will be stored...
$targetFolder = $targetFolder . basename($imgName); //adds the image name to the directory
}
$sql = "INSERT INTO products " . "(product_name,product_model,product_price,product_width,product_height,product_weight,product_quantity,product_category,product_subcategory, product_image, product_description,date_added) " . "VALUES('$product_name','$product_model','$product_price','$product_width','$product_height','$product_weight','$product_quantity', '$product_category', '$product_subcategory', '$imgName', '$product_description', NOW())";
//echo $sql;
mysql_select_db('online_store');
$result = mysql_query($sql, $conn);
$itemResult = "";
if (!$result) {
die('Could not enter data: ' . mysql_error());
}
$itemResult = "Product has been added";
if (move_uploaded_file($imgData, $targetFolder)) { // writes/stores the image in the targetfolder->ProductImages
echo "The file " . basename($imgName) . "has been uploaded!";
} else {
echo "Sorry, there was a problem uploading your file!";
}
?>
First of all in HTML form action="post" is incorrect, the action attribute should contain a path. The method attribute should contain post or get like this: method="get" or method="post".

Notice: Undefined index: image - unable to find the error

here is my error.i dont know why it is not working.i checked all the parts but i was unable to find the error.
Notice: Undefined index: image in C:\xampp\htdocs\Final\places\Ressave.php on line 27
here is my html code that pass the name of input:
<form class="form-horizontal" action="Ressave.php" method="POST" autocomplete="on">
<div class="well">
<legend>Photos</legend>
<div class="control-group">
<label class="control-label">Upload Photo: </label>
<div class="controls">
<input name="image" type="file" />
</div>
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-primary">Submit</button>
<button type="button" class="btn">Cancel</button>
</div>
</form>
Ressave.php is here and can not recieve the name here,so the error occure.....
<?php
{ // Secure Connection Script
include('../Secure/dbConfig.php');
$dbSuccess = false;
$dbConnected = mysql_connect($db['hostname'],$db['username'],$db['password']);
if ($dbConnected) {
$dbSelected = mysql_select_db($db['database'],$dbConnected);
if ($dbSelected) {
$dbSuccess = true;
} else {
echo "DB Selection FAILed";
}
} else {
echo "MySQL Connection FAILed";
}
// END Secure Connection Script
}
if(! $dbConnected )
{
die('Could not connect: ' . mysql_error());
}
{ // File Properties
$file = $_FILES['image']['tmp_name']; //Error comes from here(here is the prob!)
if(!isset($file))
echo "Please Choose an Image.";
else {
$image = addslashes(file_get_contents($_FILES['image']['tmp_name']));
$image_size = getimagesize($_FILES['image']['tmp_name']);
if($image_size == FALSE)
echo "That is not an image.";
else
{
$lastid = mysql_insert_id();
echo "Image Uploaded.";
}
}
}
{ //join the post values into comma separated
$features = mysql_real_escape_string(implode(',', $_POST['features']));
$parking = mysql_real_escape_string(implode(',', $_POST['parking']));
$noise = mysql_real_escape_string(implode(',', $_POST['noise']));
$good_for = mysql_real_escape_string(implode(',', $_POST['good_for']));
$ambience = mysql_real_escape_string(implode(',', $_POST['ambience']));
$alcohol = mysql_real_escape_string(implode(',', $_POST['alcohol']));
}
$sql = "INSERT INTO prestaurant ( ResName, Rating, Food_serve, Features, Parking, noise, Good_For, Ambience, Alcohol, Addition_info, Name, Address1, Zipcode1, Address2, Zipcode2, Address3, Zipcode3, City, Mobile, phone1, phone2, phone3, phone4, Email1, Email2, Fax, Website, image)".
"VALUES ('$_POST[restaurant_name]','$_POST[star_rating]','$_POST[food_served]','$features','$parking','$noise','$good_for','$ambience','$alcohol','$_POST[description]','$_POST[name]','$_POST[address1]','$_POST[zipcode1]','$_POST[address2]','$_POST[zipcode2]','$_POST[address3]','$_POST[zipcode3]','$_POST[city]','$_POST[mobile]','$_POST[phone1]','$_POST[phone2]','$_POST[phone3]','$_POST[phone4]','$_POST[email1]','$_POST[email2]','$_POST[fax]','$_POST[url]','$image')";
mysql_select_db('place');
$retval = mysql_query( $sql );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
mysql_close($dbConnected);
?>
If a file was not uploaded the $_FILES array will be empty. Specifically, if the file image was not uploaded, $_FILES['image'] will not be set.
So
$file = $_FILES['image']['tmp_name']; //Error comes from here(here is the prob!)
should be:
if(empty($_FILES) || !isset($_FILES['image']))
update
You will also have issues because you're missing the enctype attribute on your form:
<form class="form-horizontal" action="Ressave.php" method="POST" autocomplete="on" enctype="multipart/form-data">
In order to be able to process files in your form you need to add the enctype attribute.
<form method='POST' enctype='multipart/form-data' >
Hey i guess you have forgotten one important setting in form
enctype="multipart/form-data" this option is used when used with files eg image file etc
<form name="image" method="post" enctype="multipart/form-data">
Apart from that to extract the contents of the file you can use following options
$tmp_img_path = $_FILES['image']['tmp_name'];
$img_name = $_FILES['image']['name'];
to print all the content of a file use:
print_r($_POST['image']);
this is the code i have which successfully insert the data into mysql and retrieve from the DB.
"Index.PHP"
<html>
<head>
<title>PHP & MySQL: Upload an image</title>
</head>
<body>
<form action="index.php" method="POST" enctype="multipart/form-data">
File: <input type="file" name="image" /><input type="submit" value="Upload" />
</form>
<?php
mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("registrations") or die(mysql_error());
if(!isset($_FILES['image']))
{
echo 'Please select an image.';
}
else {
$image = addslashes(file_get_contents($_FILES['image']['tmp_name']));
echo $_FILES['image']['tmp_name'];
$image_name = addslashes($_FILES['image']['name']);
$image_size = getimagesize($_FILES['image']['tmp_name']);
if($image_size==FALSE){
echo "That's not an image.";
} else {
if(!$insert = mysql_query("INSERT INTO test_image VALUES ('','$image_name','$image')"))
{
echo "Problem uploading image.";
} else {
$lastid = mysql_insert_id();
echo "Image uploaded.<p />Your image:<p /><img src=get.php?id=$lastid>";
}
}
}
?>
</body>
</html>
this is get.PHP
<?php
mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("registrations") or die(mysql_error());
$id = addslashes($_REQUEST['id']);
$image = mysql_query("SELECT * FROM test_image WHERE id=$id");
$image = mysql_fetch_assoc($image);
$image = $image['image'];
header("Content-type: image/jpeg");
echo $image;
?>
NOTE:- please changes your DB and table name accordingly..
Thanks,
Santanu

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
index.php (Form for uplad image)
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: ' . $target_Path;
echo '<br />';
echo 'File Name: ' . $_FILES['uploadimage']['name'];
echo'<br />';
echo 'File Type: ' . $_FILES['uploadimage']['type'];
echo'<br />';
echo 'File Size: ' . $_FILES['uploadimage']['size'];
}
?>
Show Image
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);
?>

Categories