php mysql upload an image to database - php

Found several examples online on how to upload an image to a mysql database table, in binary
NOT a link or a folder in the server.
the imag isn't viewable when i try to print it
when I check the database table,it shows a bunch of data in weird format, i'm assuming the image data
here is code
if(!empty($_FILES['image']) && $_FILES['image']['size'] > 0 && !empty($_POST['name']))
{
// Temporary file name stored on the server
$tmpName = $_FILES['image']['tmp_name'];
// Read the file
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);
code for displaying image
$sql = "SELECT * FROM `photos` WHERE userName = '$currentUser'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result))
{
$content = $row['image'];
echo $content;
echo '<p id="caption">'.$row['caption'].' </p>';
}
when i try to display the image i get nothing as output, i check the database via putty, and i see a massive amount of weird characters, i'm assuming the items for the image.
ideas?

you could eventually try to replace these two lines:
$content = $row['image'];
echo $content;
with:
echo '<img src="data:image/jpeg;base64,' . base64_encode( $row['image'] ) . '" />';

Related

Displaying images from mysql database - php

I am currently having problems with displaying image from mysql database. I am able to upload an image to mysql database, however if i want to retrieve it from the database, it is displayed in Gibberish text.
Here is upload.php
if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) {
$filename = mysqli_real_escape_string($mysqli,$_FILES['image']['name']);
$tmpName = $_FILES['image']['tmp_name'];
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);
$query = "INSERT INTO `TABLES` (`image`)
VALUES( NULL,'$data')";
$result = $mysqli->query($query);
}
View.php
$mysqlquery = "SELECT * FROM TABLE";
$results = $mysqli->query($mysqlquery);
if($results->num_rows > 0){
while ($row = $results ->fetch_assoc()){
echo '<div align = "center">';
echo "<b>".$row["image"]. "<br></b>";
header("Content-type: image/jpeg");
}
}
Try this and do not forget to give image path before source
echo "<img src='your image location directory/". $row['image'] .'" >";
Oooooh... I just wish I had the answer to this one...
Some thoughts, though.
First, from personal experience I urge against storing images in the database. For one thing, your database backups will quickly become ridiculous. A more common, and better, approach is to store the images in the file system and store only the location (e.g. /img/pic03.jpg ) of the image in the database.
Next, I see you are modifying the received binary data:
$tmpName = $_FILES['image']['tmp_name'];
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);
Perhaps you know something that I don't (it's not difficult), but generally, if you gerfingerpoke with binary image data you get ... um... gibberish. Try disabling those lines and see what happens.

Cannot convert blob to image

I have a database where images are saved as blob. Now, I want to convert this blob data into image files.
So I have made this code, but its not giving any result
$sql_icon = "SELECT $off_table.icon,$off_table.id
FROM $off_table,$cnt_table,$ctg_table
WHERE $off_table.id = $cnt_table.id
AND $off_table.id = $ctg_table.id
AND ".$cond_api."
AND ".$cond_nt."
AND ".$cond_cnt."
AND ".$cond_ctg;
$result_icon = mysql_query($sql_icon);
while($row = mysql_fetch_array($result_icon))
{
$image = $row["icon"];
$id = $row["id"];
$file = fopen("./image/".$id.".jpg","w");
fwrite($file, base64_decode($image));
fclose($file);
}
The issue is, I am getting files but no extensions and if I rename them to ".jpg" extension, then its displaying "no preview available"
NOTE:
The images are saved into database by this method
$sql = "INSERT INTO aw_offers_v2
(
id,name,description,payout_type,
payout,expiration_date,creation_date,preview_url,
tracking_url,categories,countries,countries_short,
api_key,network_id, icon,icon_size)
VALUES
('$id','$name','$description','$payout_type',
'$payout','$expiration_time','$creation_time','$preview_url',
'$tracking_url','$categories','$countries','$countries_short',
'$api','$api_url','".mysql_real_escape_string(file_get_contents($cover_image_src))."','".strlen(file_get_contents($cover_image_src))."')";
If I write this code
echo '<img src="data:image/jpeg;base64,'. base64_encode($image).'" />';
then I can see the images properly. That means the images are successfully saved.
But I can't store them in folder as files.
By looking at your code, you don't base64_encode your image.
So you can just do:
fwrite($file, $image);
You only need base64_encode when you display the image putting the data inside the src attribute of <img tag.
Also note that you can simplify this:
$file = fopen(...);
fwrite($file, $image);
fclose($file);
with a single line:
file_put_contents("./image/{$id}.jpg", $image);

php displaying image from stored path?

UPDATE.
I can only display the images inside a query e.g.
if($Result = mysqli_query($Link, $Query)){
while($row = mysqli_fetch_array($Result))
{
$img = $row['path'];
echo '<img src="'.$img.'">';
}
}
I want to display them inside a table but this code doesn't work :
<td class="tcgimagecell" colspan="5"><?php echo '<img src="'.$img.'">'; ?></td>
BELOW ISSUE RESOLVED :
I have images stored in a folder (uploads) and the path is stored in a database table in a field named path. I am trying to display the stored images.
$Link = mysqli_connect($Host, $User, $Password, $Database);
$Query = "SELECT * FROM $images";
if($Result = mysqli_query($Link, $Query)){
while($row = mysqli_fetch_array($Result))
{
$img = "uploads/" . $_FILES["file"]["name"];
echo '<img src="'.$img.'">';
}
}
Your folder permissions for "uploads/" might not be set to public read. Have you checked those already? What is the URL that is output for your image? Have you tried Copying URL and linked directly to it from your browser? If the URL is coming back blank, try $row instead of $_FILES since you are just wanting the path to the file.
This line is wrong: $img = "uploads/" . $_FILES["file"]["name"];.
Replace it with $img = "uploads/" . $row[x]; where x is the number of column where file name is
OR
with $img = "uploads/" . $row['columnname'];. Here you have to replace columnname.

fetch image from mysql php

here i am trying to upload the employee profile picture to mysql and then i want to fetch those picture. now i can uploaded the image into mysql db successfully but, when i try to fetch the image that doesn't fetch properly. if you open an image in texteditor na how it will look like? the same thing i got it now.. like this... (QÕf0±Ó%"÷YúEûVÚo¾e9°R}È"!5®?•Ÿ\¯ž›ÃÕîYU0T³¼´œ\aVë%z€ÙBðŒÆnPÈ Qx•eú0´ÁPÁ”·=ó-)Oyá+×½ÄS„ÞšÅS!Y¨;,¾¤ª5HÅÓôÍó3Áº¶j/"5±•RX›ee.&{ +C˜ H CÌai,F+Ô#”?Ì8««IÐO%IW).
my question is how to fetch the image properly? and then is there any other way to do store an image to mysql db. for example save a employee profile pictures to one folder and then store that link to mysql???
index.php code:
<form enctype="multipart/form-data" action="img.php" method="post" name="changer">
<input name="image" accept="image/jpeg" type="file">
<input value="Submit" type="submit">
</form>
<?php
include("config.php");
$query = mysql_query("SELECT * FROM tbl_images");
while($row = mysql_fetch_array($query))
{
echo "" . $row['image'] . "";
}
?>
img.php code:
<?
include("config.php");
if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) {
$tmpName = $_FILES['image']['tmp_name'];
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);
$query = "INSERT INTO tbl_images ";
$query .= "(image) VALUES ('$data')";
$results = mysql_query($query, $link) or die(mysql_error());
print "Thank you, your file has been uploaded.";
}
else {
print "No image selected/uploaded";
}
?>
Can you try this,
echo '<img src="data:image/png;base64,' . base64_encode($row['image']) . '" />';
Your code:
while($row = mysql_fetch_array($query))
{
echo '<img src="data:image/png;base64,' . base64_encode($row['image']) . '" />';
}
please check the column size where you are saving the file content. The probable reason to me that you are not able to retrieve the images could be that the data is being trimmed due to size limit of the column. Try increasing the size of the column and changing the data type also, if needed. You may try the longblob datatype.
Encapsulate the echo statement in <img> tags
<form enctype="multipart/form-data" action="img.php" method="post" name="changer">
<input name="image" accept="image/jpeg" type="file">
<input value="Submit" type="submit">
</form>
<?php
include("config.php");
$query = mysql_query("SELECT * FROM tbl_images");
while($row = mysql_fetch_array($query))
{
echo "<img src=". $row['image'] . "/>"; // Do like this
}
?>
You need to have it rendered in the HTML as an img tag.
You should consider storing the image in a directory on the server and storing the image name/location in the database. Then create an img tag from that.
you must store you image in a folder and rename the file unique name along with the extension.
and store filename in mysql database table. i think the given code will help you.
<?
include("config.php");
if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) {
$tmpName = $_FILES['image']['tmp_name'];
$filename = $_FILES['image']['name'];
$ext = getExtension($filename);
$new_file = "uniquename_of_file.".$ext; // you can generate unique name by any way you want.
move_uploaded_file($_FILES['image']['tmp_name'],$DESTINATION_FOLDER."/".$new_file; // upload file to the destination folder with new name
$query = "INSERT INTO tbl_images ";
$query .= "(image) VALUES ('$new_file')";
$results = mysql_query($query, $link) or die(mysql_error()); // insert new name into the database
print "Thank you, your file has been uploaded.";
}
else {
print "No image selected/uploaded";
}
?>
function of getting extension will be as follows
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}

How to upload and display images in mysql

I would like to ask you how can I properly stored an image both in mysql and in a folder at the moment with this code:
<?php
if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) {
// Temporary file name stored on the server
$tmpName = $_FILES['image']['tmp_name'];
// Read the file
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);
// Create the query and insert
// into our database.
$query = "INSERT INTO tbl_images ";
$query .= "(images) VALUES ('$data')";
$results = mysql_query($query, $conn);
// Print results
print "Thank you, your file has been uploaded.";
}
else {
print "No image selected/uploaded";
}
if (!mysql_query($sql, $link))
{
die('Error: ' . mysql_error());
}
?>'
Also how properly to display it.
My database for the images is id, images. Do I need anything more for the job or that is enough.
Thank you.
From the above code, image will be saved in database not in folder.
To save in folder you have to use a below code after insert query.
move_uploaded_file($tmpName,"upload/" .$filename );
here upload is folder name.
If you want to store image in database you can use base64_encode method
$image = file_get_contents('filename.gif');
$imencoded = base64_encode($image);
$query = "INSERT INTO tbl_images ";
$query .= "(images) VALUES ('$imencoded')";
But storing image in db is not recommended and it will not support in IE6 & 7.

Categories