guys.
I tried to load image stored in mysql blob field with php, but the image does not show correctly. In firebug, I got these infos: get-image.php Dimensions0 × 0File size5.35KBMIME typeimage/jpeg
Here is my code
HTML
<html>
<head>
<title>Demo of Database Image in a page</title>
</head>
<body>
Here is your picture:<br>
img src=get-image.php?id=1 width=400 height=300><br>
</body>
</html>
PHP
<?php
include "db.php";
$conn = OpenDbConnection();
$key = $_GET["id"];
$tkey = "" . $key . "";
$strsql = "SELECT * FROM `images` WHERE `image_id` = " . $tkey;
$rs = mysql_query($strsql, $conn) or die(mysql_error());
if (!($row = mysql_fetch_array($rs))) {
die("File not exists.");
}
header("Content-type: image/jpeg");
echo $row["content"];
mysql_free_result($rs);
mysql_close($conn);
?>
Please someone tell me what is wrong with my code?
Please try this code.
Instead of
echo $row["content"];
Use this code
?>
<img scr="<?php echo $row["content"];?>" />
<?php
Thanks,
Kanji
Maybe it's because of blog type. Whenever you upload an image which exceed the limit of blob, then image not displayed correctly. Try to change type from blob to long blob.
Related
As title I am trying to upload images on a DB Mysql using PHP:
Here are the scripts: (I know I should use mysqli...)
form in HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="generator" content="AlterVista - Editor HTML"/>
<title> Carica un'immagine </title>
</head>
<body>
<form enctype="multipart/form-data" action="upload.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="3000000">
Invia questo elemento: <input name="userfile" type="file"></br>
<input type="submit" value="Carica">
</form>
</body>
</html>
PHP script:
<?php
//Connect to DB
$conn = mysql_connect('localhost', 'realegr', 'pass', 'my_realegr');
if (!$conn){
die("Could Not Connect to MySQL!");
}
if(!mysql_select_db("my_realegr")){
die("Could Not Open Database:" . mysql_error());
}
//file properties
$file = $_FILES['userfile']['tmp_name'];
if (!isset($file)){
echo "<p>Please Select an Image</p>";
} else {
$image = mysql_real_escape_string(file_get_contents($_FILES['userfile']['tmp_name']));
$image_name = mysql_real_escape_string($_FILES['userfile']['name']);
$image_size = getimagesize($_FILES['userfile']['tmp_name']);
if ($image_size==FALSE) {
echo "<p>NOT AN IMAGE</p>";
} else {
echo "<p>File is an Image. Processing...</p>";
if(!$insert = mysql_query("INSERT INTO images (name, image) VALUES ('$image_name','$image')")){
echo ("<p>Error Uploading Image: " . mysql_error() . "</p>");
} else {
$lastid = mysql_insert_id();
echo "<p>Success!</p>";
echo "<img src=get.php?id=$lastid>";
}
}
}
?>
Obviously there is another php script (get.php),but the problem is in this one.
The error I got is this:
File is an Image. Processing...
Error Uploading Image: Data too long for column 'image' at row 1
I can't understand the reason...(the image is of just 70 kb)
(THis is my table:
id int primary key Auto_increment
name varchar(50)
image blob
)
Don't save image data in the database. There is no need, and could even cause your site to run more slowly!
Instead, save it into an uploads folder that isn't publicly accessible using move_uploaded_file() http://php.net/manual/en/function.move-uploaded-file.php
Once you do that, store the path to the file in the DB!
Currently you have this line:"INSERT INTO images (name, image) VALUES ('$image_name','$image')". What if you attempted to change it into something like:
<?php
// NOTICE THE "LOAD_FILE"
// WHERE $fileToLoad IS THE PATH TO THE UPLOADED IMAGE-FILE
"INSERT INTO images (name, image)
VALUES('$image_name', LOAD_FILE({$fileToLoad}))";
However, storing images in the Database, from experience, is always not the very best of options...consider storing the images in a dedicated folder and simply saving only the address in your Database....
I am trying to show an image from the database to a new page using php. I am clicking on the image which needs to open in a new page. But everytime a same image is showing on the new page. I want an image in the new page which I clicked in last page. please help me.
<?php
$con = mysql_connect("localhost", "root" , "");
$sdb = mysql_select_db("display_images",$con);
$sql = "SELECT image FROM `tab1` WHERE 1";
$mq = mysql_query($sql) or die ("not working query");
$row = mysql_fetch_array($mq) or die("line 44 not working");
$s = $row['image'];
echo $row['image'];
echo '<img src="'.$s.'" alt="HTML5 Icon" style="width:800px;height:500px " >';
?>
Kindly use the below code:
<?php
$con=mysql_connect('localhost','root','');
$coo=mysql_select_db('your_db',$con);
if(!$coo)
{
echo 'error';
}
$get='select * from `your_table` where 1';
$get1=mysql_query($get);
$r=mysql_num_rows($get1);
for($j=1;$j<=$r;$j++){
$ans=mysql_fetch_array($get1);
?>
<img src="<?php echo $ans['your_field_name']?>" width="200" height ="200"
attr="<? php echo $ans['your_field_name']?>" class="image"/>
<?php }
?>
<script src="jquery.min.js" ></script>
<script>
$( document ).ready(function(){
$('.image').click(function(){
var new_image= $(this).attr('attr');
window.open( new_image );
});
});
</script>
The above code will do that just list out all the images from your table and then when you click a particular image that will displayed in the new window!!Is it your need??
mysql_query() is not preferable...Just for you!!
i have store an image into my database.
but i am unable to display the image what i have done till now is under.... any help will be appreciated. thanks in advance!
<?
$query="SELECT * from testimonial";
$ret = mysqli_query($mysql,$query);
if (isset($ret) && $ret->num_rows>0)
{
while($row=mysqli_fetch_array($ret))
{
$body=$row['body'];
$name=$row['name'];
$image=$row['img'];
?>
<li>
<div class="frame-icon"><? echo "<img src=test_img.php?id=".$row['id']." width=150 height=150/>";?></div>
<p class="quote"><?php echo $body; ?><span><?php echo $name; ?></span></p>
</li>
<?php }
echo "</table>";
}
?>
and my test_img code is
<?
<?php if (isset($_GET['id'])){
$id=mysql_real_escape_string($_GET['id']);
$query=mysql_query("SELECT *FROM testimonial WHERE id='$id' ");
while($row = mysql_fetch_assoc($query))
{
$image=$row["img"];
}
header("content-type: image/png");?>
hi Abhik i have try this one but i get something like this
and in my case i have png image so just change the jpeg to png the code you have given
but i got this <img src="data:image/png;base64,iVBORw0KGgpcMFwwXDANSUhEUlwwXDBcMGRcMFwwXDBkCAZcMFwwXDBw4pVUXDBcMFwwCXBIWXNcMFwwCxNcMFwwCxMBXDCanBhcMFwwCk9pQ0NQUGhvdG9zaG9wIElDQyBwcm9maWxlXDBcMHjanVNnVFPpFj333vRCS4iAlEtvUhUIIFJCi4AUkSYqIQkQSoghodkVUcERRUUEG8igiAOOjoCMFVEsDIoK2AfkIaKOg6OIisr74Xuja9a89+bN/rXXPues852zzwfACAyWSDNRNYAMqUIeEeCDx8TG4eQuQIEKJHBcMBAIs2Qhc/0jAVww+H48PCtcIsAHvlwwAXjTCwhcMMBNm8AwHIf/D+pCmVxcAYCEAcB0kThLCIAUXDBAeo5CplwwQEYBgJ2YJlNcMKAEXDBgy2Ni41wwUC1cMGBcJ3/m01wwgJ34mXsBXDBblCEVAaCRXDAgE2WIRFwwaDtcMKzPVopFXDBY...6B2flQRKMpIP+DXCJ7HsLarL6Op8HdHo/cKIqsCFA4DsBDRQIS30pzU8aoX9JqqWYOntZjRPR6URKyCQVTCOGPXDDMiu8BWVM0P8z8cAzyOrJpdSgciP8+C8AX4VVUgLKOiHrSGqWC6QdFLGWnXDDsXCeivfHIulwiVdcZGHyV9mig3UVcMJKeKGdE9F/oUmo/Dlww+FmRXhaI6N+6UAzZjx8x875m3kOYV2AIXCJa34ViiLYU1XDWiO/o4jBEm9P9GoWpLFwwfUVV7o1CG/J8UW1nbUi5Qy85GdUkXCLPEtFzhQJcIlwiIFwiiMh1XCKyehwb863MfGHeNWQN25BDdoEyX4nB4+tmmtkUNHdwFxFRPxH93MymmNkxRPQGEf23mR0Xq82tfRqHXDDgpeiwnBj7tdvM2MzSVL5l7n+TmXcDWGdmvYWqy/FSWP3/Rkq7Q9AFpEtdQLqAdKkLyNig/xtcMETk0l30p0FqXDBcMFwwXDBJRU5ErkJggg==">
How about if you store the location of the image in DB then store the image itself in the file system? It's a better choice I think.
Proper way to display the blob images stored in DB is
echo '<img src="data:image/jpeg;base64,' . base64_encode($row['img']) . '">';
thank's for help. I have problem displaying images retrieving from my database.
I cant see the image when loading image.php in img src or directly from the page. When i display the variable without header('Content-type: image/jpeg'); i can see all the code inside, as i put this line all goes off.
I have a table called TABLE with id, title, img stored as longblob directly uploaded inside phpmyadmin.
Can anyone help me?
index.php
<?php
session_start();
include "admin/include/connection2.php";
$data = new MysqlClass();
$data->connect();
$query_img ="SELECT * FROM table ORDER BY data ASC LIMIT 4";
$post_sql = $data->query($query_img);
if(mysql_num_rows($post_sql) > 0){
while($post_obj = $data->estrai($post_sql)){
$id = $post_obj->id;
$titolo = stripslashes($post_obj->title);
$data_articolo = $post_obj->data;
$immagine = $post_obj->img;
// visualizzazione dei dati
echo "<h2>".$titolo."</h2>";
echo "Autore <b>". $autore . "</b>";
echo "<br />";
echo '<'.'img src="image.php?id='.$post_sql['id'].'">';
echo $id;
echo "<hr>";
}
}else{
echo "no post aviable.";
}
// here is the image.php code
<?php
include "admin/include/connection2.php";
$data = new MysqlClass();
// connect
$data->connetti();
$id = $_GET['id'];
echo $id;
$query = mysql_query("SELECT * FROM articoli_news WHERE id='".$id."'"; //even tried to send id='1' but not working
echo $query;
$row = mysql_fetch_array($query);
echo $row['id']; //correct displaying
$content = base64_decode($query['img']);
header('Content-type: image/jpeg');
echo $content;
?>
Delete all "echo" commands except "echo $content;" because there are also appear in the output, and damage your image.
And use ob_start(); in the begining of the script, and check out your script file not contain any of whitespace characters before or after the php begint and close tags .
first time using stack overflow.
I have followed the following 2 part youtube tutorial on uploading/storing an image in a MYSQL database. I have followed the instructions but my image is not appearing for me. I use connect.php to connect to the database, this appears to be working fine. It seems the problem is with get.php as when I test echoing any images from it I always get no image.
used phpmyadmin to create the database and am using xampp.
here is the link to the youtube tutorials
http://www.youtube.com/watch?v=CxY3FR9doHI
http://www.youtube.com/watch?v=vFZfJZ_WNC4&feature=fvwrel
Included are the files
<html>
<head>
<title>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
include 'connect.php';
//file properties
$file = $_FILES['image']['tmp_name'];
if(!isset($file))
echo "Please select an image.";
else{
$image = addslashes(file_get_contents($_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 store 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>
Here is get.php
<?php
include 'connect.php';
$id=stripslashes($_REQUEST('id'));
$image = mysql_query("SELECT * FROM store WHERE id=$id");
$image = mysql_fetch_assoc($image);
$image=$image('image');
header("content-type: image/jpeg");
?>
And finally connect
<?php
// connect to database
$db_host="localhost";
$db_username="root";
$db_pass="";
$db_name="test";
#mysql_connect("$db_host","$db_username","$db_pass") or die("Could not connect to mysql");
mysql_select_db("$db_name")or die("Cant find database");
?>
Your get.php doesn't echo $image.
Also $image=$image('image'); should be $image=$image['image'];, and $_REQUEST('id') should be $_REQUEST['id'].
P.S. Don't use addslashes to prevent against SQL injections. Use mysql_real_escape_string.
You never echo the image data in get.php, so you're serving a blank 0-byte image.
You are missing a line after the header output
header("content-type: image/jpeg");
echo $image;
Very quick glance, in get.php change:
$image=$image('image');
to
$image=$image['image'];
mysql_fetch_assoc() converts the results into an array.
You better of bas64_encoding an decoding that way none ansi chars wont create a problem.
base64_encode(file_get_contents($_FILES['image']['tmp_name']));
This is wrong as array is [] not ()
include 'connect.php';
$id=stripslashes($_REQUEST('id'));
$image = mysql_query("SELECT * FROM store WHERE id=$id");
$image = mysql_fetch_assoc($image);
$image=$image['image'];
header("content-type: image/jpeg");
echo base64_decode($image);
Piece of code I use in a site of mine:
<?php
ob_start();
require_once("db.php.lib");
DBLogin();
$sql = "select pic_user_id, pic_full_data as bindata, pic_full_mime as mime, pic_full_size as size from pics where pic_name = '".urldecode($_GET["pic_name"])."'";
$result = DBExec($sql);
if ($result)
{
$row = DBGetNextRow($result);
if ($row)
{
header("Content-type: ".$row["mime"]);
header("Content-length: ".$row["size"]);
ob_clean();
echo $row["bindata"];
ob_end_flush();
}
}
?>
It looks like you're leaving out the actual output of the image data, and the length might be required by some browsers...