I am trying to display an image from my php page by saving the image in the database [MySql] and when I retrieve it it did't show me the image.
However, I can see the image when I click on it in MySql, but it is not shown in the php file.
Images Table:
id INT
image BLOB
index.php
<html>
<head>
<title>Uploade an image</title>
</head>
<body>
<form action="test_image.php" method="POST" enctype="multipart/form-data">
File:
<input type="file" name="image"> <input type="submit" value="Uploade">
</form>
<?php
mysql_connect("", "", "")
or die("<p>Error connecting to database: " . mysql_error() . "</p>");
mysql_select_db("test")
or die("<p>Error selecting the database: " . mysql_error() . "</p>");
// file propoerties
$file = $_FILES['image']['tmp_name'];
if(!isset($file))
echo "Please select 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's not an image";
else
{
if(!$insert = mysql_query("INSERT INTO Images (image) VALUES ('$image')"))
echo "Problem uploading image.";
else
{
$lastid = mysql_insert_id();
echo "Image uploaded <p /> Your image: <p /> <img width='500' height='500' src=getimage.php?id=$lastid>";
}
}
}
?>
</body>
</html>
getimage.php
<?php
mysql_connect("", "", "")
or die("<p>Error connecting to database: " . mysql_error() . "</p>");
mysql_select_db("test")
or die("<p>Error selecting the database: " . mysql_error() . "</p>");
$id = addslashes($_REQUEST['id']);
$image = mysql_query("SELECT * FROM Images WHERE id = $id");
$image = mysql_fetch_assoc($image);
$image = $image['image'];
header("Content-type: image/jpeg");
echo $image;
?>
I can upload the image but I can't retrieve it!!
Thank you,
you need to use img html element to view the image
for example
src here is where you are saving your image file
<img src="images/yoursavedimagenameindatabase" width="" height="">
Then you can view your saved images in view
$path="images/.$image['image']."
echo '<img width="100" height="66" src="'.$path.'" />';
Related
Hi i have a code which is uploading file and saving its path in database. Now i want to change its path to its corresponding id with which it is saving in database i.e i have uploaded an image and its id is '4' in database and its file path should also be 4. and if i upload an other image and if its id is 5 then in its file path column there should also be 5 and so on. I have searched for a while but i'm not able to find the proper answer. Kindly help me here.
Here is my code
directory-image.php
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>image in directory</title>
</head>
<body>
<form method="post" action="directory-imagedatabase.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" id="upload" />
</form>
</body>
</html>
directory-imagedatabase.php
<?php
$target_Folder = 'images/';
$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('officework/php-startup/images/'.$file_name))
{
echo "That File Already Exisit";
}
else
{
// Database
$con=mysqli_connect("localhost","root","sal123","test"); //Change it if required
//Check Connection
if(mysqli_connect_errno())
{
echo "Failed to connect to database" . mysqli_connect_errno();
}
$sql = "INSERT INTO directoryimage (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'];
}
}
?>
Get the record's insert ID $id = mysqli_insert_id($con) after the INSERT
Get file extension: $ext = preg_replace("/\.(gif|jpg|etc)$/", ".$1", $file_name);
Rename the file with rename() rename("$target_Folder$file_name", $id . $ext);
Update the record with something like $sql = "UPDATE directoryimage SET image = CONCAT('{$target_Folder}', id, '{$ext}') WHERE id = $id";
I've been trying my head at this for ages, check every possible place on Google,
and sometimes I feel brain dead by just doing this.
I'm doing this for the fun of it but I am stuck on this particular aspect of displaying an image from a MySQL database using BLOB.
As far as I know I think I am uploading the image correctly, but whenever I try to display the image, it ends up just giving me the default image icon and the name of the image, Then when I inspect source, it comes up with gibberish for the image.
Can someone please tell me what I'm doing wrong?
show_profile.php
<html>
<body>
View Records
Logout
<div id="body_show">
<link href="show_profile.css" rel="stylesheet" type="text/css">
<div id="image" class="image" style="width: 152px; height:152px;">
<?php
include('database_connection.php');
if(session_id() ==""){
session_start();
}
$username = $_SESSION['myusername'];
$query = "SELECT * FROM $dImage_table WHERE username='$username' and imageID = (SELECT MAX(imageID) FROM $dImage_table WHERE username='$username')";
$result=mysqli_query($DBConn, $query);
if(!$result){
$message = "<p>
There was an error with the query.<br />\n" .
"The error was " .
htmlspecialchars(mysqli_error($DBConn), ENT_QUOTES) .
".<br />\nThe query was '" .
htmlspecialchars($query, ENT_QUOTES ) .
"'</P>\n";
}
else if (!mysqli_num_rows($result)){
$message = "<p>Cannot find Image in the database.</p>\n";
}
else{
while($report = mysqli_fetch_assoc($result)){
$imageData = $report['image'];
$imageName = $report['imageName'];
$imageType = $report['imageType'];
$imageID = $report['imageID'];
//echo "<img src="'data:image;base64,'.$imageData."' alt='Image'/>";
//echo "<img src=data:$imageType;base64,base64_encode($imageData) alt=$imageName width=152px height=152px/>";
echo '<img src="data:'.$imageType.';base64,'. base64_encode($imageData).'" alt="'.$imageName.'" width="152px" height="152px" />';
//echo "</br>";
}
//echo $imageData;
}
?>
</div>
<div class="form_body">
<form id="form_body" action="pic_uploader.php" method="POST" enctype="multipart/form-data">
<input type="file" name="image"><input type="submit" name="submit" value="Upload">
</form>
<div>
<?php
//echo $message;
?>
</div>
</body>
pic_uploader.php
<?php
include('database_connection.php');
session_start();
if(isset($_POST['submit']))
{
$username = $_SESSION['myusername'];
$imageName = mysqli_real_escape_string($DBConn, $_FILES["image"]["name"]);
$imageData = mysqli_real_escape_string($DBConn, file_get_contents($_FILES["image"]["tmp_name"]));
$imageType = mysqli_real_escape_string($DBConn, $_FILES["image"]["type"]);
$imageData= base64_encode($imageData);
if(!substr($imageType,0,4) == "image")
{
$message = "<p>Only Images are allowed!</p>";
include 'show_profile.php';
}
else{
$query = 'INSERT INTO dImage_table (username, imageID, imageName, imageType, image)
VALUES("'.$username.'",
"'. "" .'",
"'.$imageName.'",
"'.$imageType.'",
"'.$imageData.'")';
if(!mysqli_query($DBConn, $query))
{
$message = "<p>
There was an error uploading the image.<br />\n" .
"The error was " .
htmlspecialchars(mysqli_error($DBConn), ENT_QUOTES) .
".<br />\nThe query was '" .
htmlspecialchars($query, ENT_QUOTES ) .
"'</P>\n";
}
else
{
$message = "<p>Image uploaded</p>";
include 'show_profile.php';
}
}
}
?>
Thanks for your input
Upload the image to a web server and store the url of the image, never seen anyone store the image directly into a mysql database. Here's a simple tutorial on how to upload files: http://www.w3schools.com/php/php_file_upload.asp
I am trying to upload images to my database.
This is the form.
<form action='index.php' method='POST' enctype='multipart/form-data'>
<label>Change Profile Pic</label> <br>
<input type='file' name='image'> <input type='submit' name=submitpicture
value='Upload'>
</form>
This is the set of functions.
if(isset($_POST['submitpicture']))
{
$link = mysqli_connect('localhost','root','*****','*****');
$image = file_get_contents($_FILES['image']['tmp_name']);
$imagename = ($_FILES['image']['tmp_name']);
$image_size = getimagesize($_FILES['image']['tmp_name']);
if($image_size== false)
{
echo "This is not an image.";
}
else
{
if(!$link) //This links to my database.
{
echo "No link";
}
else
{
$picturedatabase = "INSERT INTO databaseimage ('name','image') VALUES ('name','$image')";
if(mysqli_query($link,$picturedatabase));
{
echo "Entered into database";
}
}
}
}
When I upload an image, I get echoed back "Entered into Database" but when I check my database there are no rows. What am I doing wrong?
Instead, set image like this:
$image= 'data:image/' . $type . ';base64,' . base64_encode(file_get_contents($_FILES['image']['tmp_name']));
Then, when you put it as an image src it will display the image. This also will reduce requests.
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".
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);
?>