How to display image from database using php [duplicate] - php

This question already has answers here:
How to retrieve images from MySQL database and display in an html tag
(4 answers)
Closed 1 year ago.
I am trying to display an image coming from the database and I was not able to display the image .but its showing like this user-1.jpg Please see my code can one guide me how to display the image.
$sqlimage = "SELECT image FROM userdetail where `id` = $id1";
$imageresult1 = mysql_query($sqlimage);
while($rows = mysql_fetch_assoc($imageresult1))
{
$image = $rows['image'];
print $image;
}

Displaying an image from MySql Db.
$db = mysqli_connect("localhost","root","","DbName");
$sql = "SELECT * FROM products WHERE id = $id";
$sth = $db->query($sql);
$result=mysqli_fetch_array($sth);
echo '<img src="data:image/jpeg;base64,'.base64_encode( $result['image'] ).'"/>';

For example if you use this code , you can load image from db (mysql) and display it in php5 ;)
<?php
$con =mysql_connect("localhost", "root" , "");
$sdb= mysql_select_db("my_database",$con);
$sql = "SELECT * FROM `news` WHERE 1";
$mq = mysql_query($sql) or die ("not working query");
$row = mysql_fetch_array($mq) or die("line 44 not working");
$s=$row['photo'];
echo $row['photo'];
echo '<img src="'.$s.'" alt="HTML5 Icon" style="width:128px;height:128px">';
?>

<?php
$connection =mysql_connect("localhost", "root" , "");
$sqlimage = "SELECT * FROM userdetail where `id` = '".$id1."'";
$imageresult1 = mysql_query($sqlimage,$connection);
while($rows = mysql_fetch_assoc($imageresult1))
{
echo'<img height="300" width="300" src="data:image;base64,'.$rows['image'].'">';
}
?>

You need to do this to display image
$sqlimage = "SELECT image FROM userdetail where `id` = $id1";
$imageresult1 = mysql_query($sqlimage);
while($rows=mysql_fetch_assoc($imageresult1))
{
$image = $rows['image'];
echo "<img src='$image' >";
echo "<br>";
}
You need to use html img tag.

put you $image in img tag of html
try this
echo '<img src="your_path_to_image/'.$image.'" />';
instead of
print $image;
your_path_to_image would be absolute path of your image folder like eg: /home/son/public_html/images/ or as your folder structure on server.
Update 2 :
if your image is resides in the same folder where this page file is exists
you can user this
echo '<img src="'.$image.'" />';

instead of print $image; you should go for print "<img src=<?$image;?>>"
and note that $image should contain the path of your image.
So,
If you are only storing the name of your image in database then instead of that you have to store the full path of your image in the database like /root/user/Documents/image.jpeg.

Simply replace
print $image;
with
echo '<img src=".$image." >';

$sqlimage = "SELECT image FROM userdetail where `id` = $id1";
$imageresult1 = mysqli_query($link, $sqlimage);
while($rows=mysqli_fetch_assoc($imageresult1))
{
echo "<img src = 'Image/".$row['image'].'" />';
}

<?php
$conn = mysql_connect ("localhost:3306","root","");
$db = mysql_select_db ("database_name", $conn);
if(!$db) {
echo mysql_error();
}
$q = "SELECT image FROM table_name where id=4";
$r = mysql_query ("$q",$conn);
if($r) {
while($row = mysql_fetch_array($r)) {
header ("Content-type: image/jpeg");
echo $row ["image"];
}
}else{
echo mysql_error();
}
?>
sometimes problem may occures because of port number of mysql server is incoreect to avoid it just write port number with host name like this "localhost:3306"
in case if you have installed two mysql servers on same system then write port according to that
in order to display any data from database please make sure following steps
1.proper connection with sql
2.select database
3.write query
4.write correct table name inside the query
5.and last is traverse through data

put this code to your php page.
$sql = "SELECT * FROM userdetail";
$result = mysqli_query("connection ", $sql);
while ($row = mysqli_fetch_array($result,MYSQLI_BOTH)) {
echo "<img src='images/".$row['image']."'>";
echo "<p>".$row['text']. "</p>";
}
i hope this is work.

Related

Prevent image from going to next line

I have a working code that pulls image blobs from the MYSQL Table and shows them on my web page. It works for the most part but the problem I am running into is how to not make it move to the next line as shown in my picture below. Is there anyway to do this?
<?php
$id ='1';
$db = mysqli_connect("localhost","brianrob_usr","","brianrob_productdb"); //keep your db name
$sql = "SELECT * FROM Products WHERE id = $id";
$sth = $db->query($sql);
while($row = $sth->fetch_array()){
echo '<div><img src="data:image/jpeg;base64,'.base64_encode( $row['Image'] ).'"/></div>';
}
?>
#charset "utf-8";
/* CSS Document */
body{
width: inherit;
height:inherit;
background-image: url("007-dark-loom.png");
}
as Given by ADyson, Removing the tags helped fix this issue.
<?php
$id ='1';
$db = mysqli_connect("localhost","brianrob_usr","Ilikecandy2009","brianrob_productdb"); //keep your db name
$sql = "SELECT * FROM Products WHERE id = $id";
$sth = $db->query($sql);
while($row = $sth->fetch_array()){
echo '<img src="data:image/jpeg;base64,'.base64_encode( $row['Image'] ).'"/>';
}
?>

How to get images from database (blob column) on the same page using pdo or mysqli ?? PHP

I am facing an issue to get images from database. I went through so many articles of stack and other websites also, but none have the solution I am looking for. How can I get images stored in the database on the page?
Here is the code, kindly check it and let me know what mistake I made. All help is really appreciated.
<?php
// I have database name databaseimage
// I have a table named store
// I have 3 columns into the table store
// id (int primary key ai), name (varchar), and image (longblob)
// prevent accesing the page directly
if($_SERVER['REQUEST_METHOD'] !='POST') {
echo "you can not acces this page directly";
die();
}
else {
print_r($_FILES);
// file properties
$file = $_FILES['image']['tmp_name'];
echo "<br>$file";
if(!isset($file)){
echo "please select an image";
die();
} else {
//actual image
$image = addslashes(file_get_contents($_FILES['image']['tmp_name'])) ;
// image name
$image_name = addslashes($_FILES['image']['name']);
echo "<br> image name is = $image_name";
//geting image size to check whether it is actually an image or not
$image_size = getimagesize($_FILES['image']['tmp_name']);
echo "<br>";
print_r($image_size);
if($image_size==FALSE) {
echo "plese select an images only";
die();
}
else {
#code to put an image into the database
// connect to database
try {
$con = new PDO("mysql:host=localhost;dbname=databaseimage", "root",
"");
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "<br>connection succesfull";
// make a query
$extr = $con->prepare("INSERT INTO store (name, image)
VALUES (:na , :im)" );
//$a=1;
//$extr->bindParam(':i', $a);
$extr->bindParam(':na', $image_name);
$extr->bindParam(':im', $image, PDO::PARAM_LOB);
if ( $extr->execute()==true) {
echo "<br>image uploaded succesfully";
# insert is working. I can insert images into database
# but really facing problem while displaying those images
# below is the code I tried
# CODE for to show uploaded files
# to show images which is uploaded
$show = $con->prepare("SELECT * FROM store ");
//$a = 1;
//$show->bindParam(':iam', $a);
$show->execute();
while ($row = $show->fetch(PDO::FETCH_BOUND) ) {
# SHOW IMAGES
//echo "<img src = '$row[image]' alt='image' >";
echo '<img src= "data:image/png;base64,'.base64_encode($row['image']).'"
height="100" width="100" />';
}
} else {
echo "<br>image not uploaded";
}
}
catch(Exception $e)
{
echo "<br> Connection failed: " . $e->getMessage();
}
}
}
// disconnect the connection
$con = null;
}
?>
Step 1: create a php script with filename getimage.php with the
following code:
<?php
$id = $_GET['id'];
// do some validation here to ensure id is safe
$con = new PDO("mysql:host=localhost;dbname=databaseimage", "root",
"");
$sql = "SELECT image FROM store WHERE id=$id";
$stmt=$con->query($sql);
$res=$stmt->fetch(PDO::FETCH_ASSOC);
$con=null;
header("Content-type: image/pn")g;
echo $res['image'];
?>
Step 2: In your current php page (below the comment "# below is the code i tried") try the following code:
$show = $con->prepare("SELECT id FROM store ");
//$a = 1;
//$show->bindParam(':iam', $a);
$show->execute();
while ($row = $show->fetch(PDO::FETCH_NUM) ) {
# SHOW IMAGES
echo '<img src="getimage.php?id="'.$row[0].'"
height="100" width="100" />';
}

How do i display images stored as blob data type in mysql with php? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
How do i display an image stored in mySQL database as BLOB ?
What it tried so far:
1. Created a new php function/file to get picture (getpicture.php).
2. In the html, I have the following code:
<img src="getpicture.php?id=2" border ="0" height="250" width="250" />
/*below is the getpicture.php*/
<?php
# $db = new MySQLi('localhost','root','','myDatabase');
if(mysqli_connect_errno()) {
echo 'Connection to database failed:'.mysqli_connect_error();
exit();
}
if(isset($_GET['People_Id'])) {
$id = mysqli_real_escape_string($_GET['People_Id']);
$query = mysqli_query("SELECT * FROM 'people' WHERE 'People_Id' = '$id'");
while($row = mysqli_fetch_assoc($query)) {
$imageData =$row['image'];
}
header("content-type: image/jpeg");
echo $imageData;
echo $id;
}
else {
echo "Error!";
echo $id;
}
?>
What's wrong with the codes ? Please help!
I answered my own question, it's working now..
Below is the getpicture.php:
<?php
$db = new MySQLi('localhost', '', '', 'mydatabase');
if ($db->connect_errno) {
echo 'Connection to database failed: '. $db->connect_error;
exit();
}
if (isset($_GET['id'])) {
$id = $db->real_escape_string($_GET['id']);
$query = "SELECT `Picture` FROM member WHERE `Id` = '$id'";
$result = $db->query($query);
while($row = mysqli_fetch_array($result)) {
$imageData = $row['Picture'];
header("Content-type:image/jpeg");
echo $imageData;
}
}
?>
The php script which retrieve the getpicture.php above looks like this:
echo '<img src="getpicture.php?id=' . htmlspecialchars($_GET["id"]) . '"border ="0" height="250" width="250" />';
Thaank you all for the help
This is wrong:
$query = mysqli_query("SELECT * FROM 'people' WHERE 'People_Id' = '$id'");
you use wrong quotes for table name (must be backtick instead of single quote (see tylda ~ key). See docs: http://dev.mysql.com/doc/refman/5.1/en/reserved-words.html
Also this is wrong too
header("content-type: image/jpeg");
echo $imageData;
echo $id;
get rid of last echo $i; and replace it with exit(); otherwise you corrupt the image data stream you just sent.
Plenty is wrong.
your SQL is wrong. Remove the single quotes from the table and column and replace with back ticks.
Although it may still work, you should have a couple of new lines after your header
You shouldn't echo out your $id after you echo your image data.
You're checking for the wrong value when you check isset
Also, you should be using OOP for mysqli
Since your image data is only a single row, you don't need to wrap it in a while loop
Here is an updated code example
<?php
$db = new MySQLi('localhost', 'user', 'password', 'myDatabase');
if ($db->connect_errno) {
echo 'Connection to database failed: '. $db->connect_error;
exit();
}
if (isset($_GET['id'])) {
$id = $db->real_escape_string($_GET['id']);
$result = $db->query("SELECT * FROM `people` WHERE `People_Id` = '$id'");
$row = $result->fetch_assoc();
$imageData = $row['image'];
header("Content-type: image/jpeg\n\n");
echo $imageData;
}
else {
echo "Error!";
}

delete images through database and directory

can somebody help me for my codes. i can delete the image in the database but in the directory i can't. im tried for long hours but it seems not work at all. would somebody help me please? here's my code: this is the code where the images
<?
//this is were images displayed
$query = "SELECT * FROM images WHERE category='home'";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
?>
<img src="images/template/delete.png" id="AEDbutton">
echo "<img border=\"0\" src=\"".$row['image']."\" width=\"200\" height=\"100\">";
echo "<br>"; }
?>
,?
include('global.php');
//this is were image were deleted
if($delete != "")
{
$query = "DELETE FROM images WHERE imageID='".$delete."'";
ExecuteQuery($query);
}
//but in here , it cannot delete image through directory
$query = "SELECT * FROM images WHERE imageID='".$delete."'";
$result = mysql_query($query);
while ($delete = mysql_fetch_array($result)) {
$image = $delete['image'];
$file= '/.directory/'.$image;
unlink($file);
}
?>
You already deleted the image entry in table, after that you try to get the same entry in DB. so, first you can delete the image from folder after that you can delete in the table.
<?php
include('global.php');
if($delete != "") {
$query = "SELECT * FROM images WHERE imageID='".$delete."'";
$result = mysql_query($query);
while ($delete = mysql_fetch_array($result)) {
$image = $delete['image'];
$file= '/.directory/'.$image;
unlink($file);
}
$query = "DELETE FROM images WHERE imageID='".$delete."'";
ExecuteQuery($query);
}
?>
Note:
Make sure your path $file= '/.directory/'.$image; is correct, I think it referring from root directory.
Funny. That's because you are first deleting the image id from the database and after that you are trying to get the ID of the previously deleted image (which no longer exists) and delete the file associated with it. Switch the code like this.
include('global.php');
if($delete != "")
{
//first delete the file
$query = "SELECT * FROM images WHERE imageID='".$delete."'";
$result = mysql_query($query);
while ($delete = mysql_fetch_array($result))
{
try
{
$image = $delete['image'];
$file= '/images/'.$image;
unlink($file);
} catch (Exception $e) {
}
}
// after that delete the id from the db of that image associated with the deleted file
$query = "DELETE FROM images WHERE imageID='".$delete."'";
ExecuteQuery($query);
}
UPDATE: I added a try catch
If you are deleting images, first you need to delete image and then delete in DB

How to delete an image using PHP & MySQL?

I was wondering if some one can give me an example on how to delete an image using PHP & MySQL?
The image is stored in a folder name thumbs and another named images and the image name is stored in a mysql database.
Delete the file:
unlink("thumbs/imagename");
unlink("images/imagename");
Remove from database
$sql="DELETE FROM tablename WHERE name='imagename'"
$result=mysql_query($sql);
Assuming name is the the name of the field in the database holding the image name, and imagename is the image's name.
All together in code:
$imgName='sample.jpg';
$dbFieldName='name';
$dbTableName='imageTable';
unlink("thumbs/$imgName");
unlink("images/$imgName");
$sql="DELETE FROM $dbTableName WHERE $dbFieldName='$imgName'";
mysql_query($sql);
try this code :
$img_dir = 'image_directory_name/';
$img_thmb = 'thumbnail_directory_name/';// if you had thumbnails
$image_name = $row['image_name'];//assume that this is the image_name field from your database
//unlink function return bool so you can use it as conditon
if(unlink($img_dir.$image_name) && unlink($img_thmb.$image_name)){
//assume that variable $image_id is queried from the database where your image record your about to delete is...
$sql = "DELETE FROM table WHERE image_id = '".$image_id."'";
$qry = mysql_query($sql);
}else{
echo 'ERROR: unable to delete image file!';
}
Are you looking for actual code or just the idea behind it?
You'll need to query the db to find out the name of the file being deleted and then simply use unlink to delete the file in question.
so here's some quick code to get you started
<?php
$thumb_dir = "path/to/thumbs/";
$img_dir = "path/to/images/";
/* query your db to get the desired image
I'm guessing you're using a form to delete the image?
if so use something like $image = $_POST['your_variable'] to get the image
and query your db */
// once you confirm that the file exists in the db check to see if the image
// is actually on the server
if(file_exists($thumb_dir . $image . '.jpg')){
if (unlink($thumb_dir . $image . '.jpg') && unlink($img_dir . $image . '.jpg'))
//it's better to use the ID rather than the name of the file to delete it from db
mysql_query("DELETE FROM table WHERE name='".$image."'") or die(mysql_error());
}
?>
if(!empty($_GET['pid']) && $_GET['act']=="del")
{
$_sql = "SELECT * FROM mservices WHERE pro_id=".$_GET['pid'];
$rs = $_CONN->Execute($_sql);
if ($rs->EOF) {
$_MSG[] = "";
$error = 1;
}
if ($rs)
$rs->close();
if (!$error) {
$_Image_to_delete = "select pro_img from mservices where pro_id=".$_GET['pid'];
$trial=$_CONN->Execute($_Image_to_delete);
$img = trim(substr($trial,7));
unlink($_DIR['inc']['product_image'].$img);
$_sql = "delete from mservices where pro_id=".$_GET['pid'];
$_CONN->Execute($_sql);
header("Location: ".$_DIR['site']['adminurl']."mservices".$atend."suc".$_DELIM."3".$baratend);
exit();
}
}
$_sql = "SELECT * FROM mservices WHERE pro_id=".$_GET['pid'];
$rs = $_CONN->Execute($_sql);
if ($rs->EOF) {
$_MSG[] = "";
$error = 1;
}
if ($rs)
$rs->close();
if (!$error) {
$_Image_to_delete = "select pro_img from mservices where pro_id=".$_GET['pid'];
$trial=$_CONN->Execute($_Image_to_delete);
$img = trim(substr($trial,7));
unlink($_DIR['inc']['product_image'].$img);
$_sql = "delete from mservices where pro_id=".$_GET['pid'];
$_CONN->Execute($_sql);
header("Location: ".

Categories