Trouble displaying images from MySQL database - php

My problem is thatmy code will only display one image from my database. I change the id to a different row, the name and everything else comes up fine but the image wont load. Even if I upload a new image this still happens? Please help!
<?php
session_start();
$user = $_SESSION['username'];
if(!empty($_SESSION['loggedin'])) {
$id = $_GET['id'];
$conn = new PDO ("mysql:host=localhost;dbname=project", "root",
"pass");
$stmt = $conn->prepare("SELECT * FROM images where id = :id");
try {
$stmt->bindParam(':id', $id);
$stmt->execute();
while ($row = $stmt->fetch())
{
if($row == false)
{
echo "Sorry nothing here!";
}
else {
echo "$row[title]";
echo '<img src="data:image/jpeg;base64,' . base64_encode( $row['image'] ) . '" />';
echo "$row[username]";
echo "$row[description]";
echo "$row[category]";
}
}
}
catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>
What could be causing this? The images are stored as long blobs, their file types vary between jpg, jpeg, png and gif.
I have also tried the following which still works the same as above:
$image = $row['image'];
echo '<img src="data:image/jpeg;base64,'. base64_encode($image) .'" />';

Related

Add code around one particular result from SELECT statement

I have the following code SELECTING the Title and Image from the "Courses" table in my database.
<?php
$username = 'REMOVED';
$password = 'REMOVED';
try {
$conn = new PDO('mysql:host=localhost;dbname=REMOVED', $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare('SELECT Title, Image FROM Courses');
$stmt->execute();
while($row = $stmt->fetch()) {
print_r($row);
}
}
catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
?>
How can I make it so that the Title has a header tag wrapped around it and the Image is inside of an image src=""?
depending on your PDO settings the result may for example be returned in an associative array (which would be the most common default setting):
while($row = $stmt->fetch()) {
echo '<img src="' . $row["Image"] . '" title="' . $row["Title"] . '">';
}
update: to force the fetching of associative array, just replace $stmt->fetch() with $stmt->fetch((PDO::FETCH_ASSOC)
replace while loop with following code:
$string="<header>";
$imagesrc="";
While($row=$stmt->fetch()){
$string+=$row['Title'];
$imagesrc=$row['Image'];
}
$string+="</header>";
$stringImage="<img src='".$imagesrc."' />";

broken file icon retrieving image from database php and mysql

I need to upload and retrieve image from a database, I am able to store the image in the database but unable to display it later. please help
I wrote the following code to retrieve from the database.
$result1=mysql_query("INSERT INTO userdata(id, username, firstname, lastname, imageType, image)VALUES('', '" . $_SESSION['username'] . "', '" . $_SESSION['firstname'] . "', '$lastname','{$image_size['mime']}','{$imgData}')") or die("Invalid query: " . mysql_error());
if($result1)
{
echo "</br>";
echo "Registration successful";
echo "</br>";
echo $lastid=mysql_insert_id();//get the id of the last record
echo "uploaded image is :"; ?>
<img src="imageView.php?image_id=<?php echo $lastid; ?>" /><br/>
<?php
echo "</br>";
}#if result1into db successful
else
{
echo $result1;
echo "Problem in database operation";
imageView.php has the following code:
<?php
$conn = mysql_connect("localhost", "root", "");
mysql_select_db("wordgraphic") or die(mysql_error());
if(isset($_GET['id'])) {
$sql = "SELECT imageType,image FROM userdata WHERE id=". $_GET['image_id'];
$result = mysql_query("$sql") or die("<b>Error:</b> Problem on Retrieving Image BLOB<br/>" . mysql_error());
$row = mysql_fetch_array($result);
header("Content-type: " . $row["imageType"]);
echo $row["image"];
}
mysql_close($conn);
?>
What could be possibly wrong with the code?
When i try to run imageView.php with static id image is getting displayed. So i guess the error is in passing the variable is this code:
echo "uploaded image is :"; ?>
<img src="imageView.php?image_id=<?php echo $lastid; ?>" /><br/>
<?php
what could be possibly wrong?
just a smal rectification
<img src="imageView.php?image_id=<?php echo $lastid; ?>" />
instead of this
src = src path where u r saving the image file lets say in images folder that would be here $imagedata store the file name in the DB so that you can retreive it from the image folder
<img src="images/$imgData" width="your wish" height="your wish"/>

image does not fetch from database using path

I'm trying to upload and fetch images from database using path. Upload process working perfectly. But, I cannot able to fetch image from db. I've tried print_r($row['image']);. I'm getting the path like this C:/xampp/htdocs/xampp/htdocs/www/images/0d13808ad672c2713d306efbb0e42918. I don't know why this code doesn't fetch image from db?
fetch.php
<?php
include('config.php');
ini_set('display_startup_errors',1); a
ini_set('display_errors',1);
error_reporting(-1);
try
{
$stmt = $conn->prepare("SELECT * FROM imgdb WHERE id = 3");
$conn->errorInfo();
// $stmt->bindParam('1', $imgid, PDO::PARAM_INT);
$stmt->execute();
// $path = "/xampp/htdocs/www/images/";
// $imgpath = $_SERVER['DOCUMENT_ROOT'].$path;
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
echo "<img src=".$row['image']." height='100' width='100'/>";
print_r($row['image']);
}
}
catch (PDOException $e)
{
echo 'Database Error'.$e->getMessage();
}
?>
upload.php
<?php
ini_set('display_startup_errors',1);
ini_set('display_errors',1);
error_reporting(-1);
include('config.php');
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
else
{
// echo "Upload: " . $_FILES["file"]["name"] . "<br>";
// echo "Type: " . $_FILES["file"]["type"] . "<br>";
// echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
// echo "Stored in: " . $_FILES["file"]["tmp_name"];
}
$filename = basename($_FILES['file']['tmp_name']);
$newname = md5($filename);
$final_save_dir = '/xampp/htdocs/www/images/'.$newname ;
if(move_uploaded_file($_FILES['file']['tmp_name'], $final_save_dir . $_FILES['file']['name']))
{
echo "Uploaded";
}
else
{
echo "File was not uploaded";
}
$imgid = $_SERVER['DOCUMENT_ROOT'].$final_save_dir;
try
{
$stmt = $conn->prepare("INSERT INTO imgdb ( image ) VALUES ( ? ) ");
$stmt->bindParam('1', $imgid, PDO::PARAM_STR);
$conn->errorInfo();
$stmt->execute();
}
catch (PDOException $e)
{
echo 'Database Error'.$e->getMessage();
}
?>
Try this and compare with yours, I don't know if it works because I didn't tested, but it should.
upload.php
include('config.php');
if ($_FILES["file"]["error"] > 0 )
{
echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
else
{
$filename = basename($_FILES['file']['tmp_name']);
$ext = pathinfo($_FILES["file"]["name"], PATHINFO_EXTENSION);
$new_file_name = md5($filename).'.'.$ext;
$final_save_dir = $_SERVER['DOCUMENT_ROOT'].DS.'www'.DS.'images'.DS;
if(move_uploaded_file($_FILES['file']['tmp_name'], $final_save_dir . $new_file_name))
{
echo "Uploaded";
}
else
{
echo "File was not uploaded";
}
try
{
$stmt = $conn->prepare("INSERT INTO imgdb ( image ) VALUES ( ? ) ");
$stmt->bindParam('1', $new_file_name, PDO::PARAM_STR);
$conn->errorInfo();
$stmt->execute();
}
catch (PDOException $e)
{
echo 'Database Error'.$e->getMessage();
}
}
fetch.php
<?php
include('config.php');
ini_set('display_startup_errors',1);
ini_set('display_errors',1);
error_reporting(-1);
try
{
$stmt = $conn->prepare("SELECT * FROM imgdb WHERE id = 3");
$conn->errorInfo();
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
echo "<img src='images/".$row['image']."' height='100' width='100'/>";
}
}
catch (PDOException $e)
{
echo 'Database Error'.$e->getMessage();
}
When you link the image, you have to link to an HTTP accessible path.
Use '/' instead of $_SERVER['DOCUMENT_ROOT'] to have a path relative to the web root of your page or 'http://' . $_SERVER['HTTP_HOST'] . '/' (first one is better as the protocol is not defined so it will work on both http and https connections)
Two things
move_uploaded_file($_FILES['file']['tmp_name'], $final_save_dir . $_FILES['file']['name']) moves the file from the temp location to $final_save_dir.$_FILES['file']['name'] which is different from the value you are storing in the db which is $_SERVER['DOCUMENT_ROOT'].$final_save_dir. You will need to sync these two variables.
Just like #mrgeek pointed you are trying to retrieve an image using the absolute filesystem path not using a http url. if you are using filesystem path you need to use file:/// prepended to the location. But i'm sure this is going to be hosted somewhere so that will not help. so best bet is to use relative urls so that the browser will be able to access it
Have been trying to retrieve image from my database with this code, but it just displays a blank page. Need help
$user="root";
$host="localhost";
$pass="name";
$db="name";
$link=mysql_connect($host,$user,$pass);
if(!$link)die(mysql_error());
mysql_select_db($db,$link) or die("could not select database.");
$query_image = "SELECT * FROM img WHERE id=12";
// This query will show you all images if you want to see only one image pass acc_id='$id' e.g. "SELECT * FROM acc_images acc_id='$id'".
$result = mysql_query($query_image);
if(mysql_num_rows($result) > 0)
{
while($row = mysql_fetch_array($result))
{
echo '<img alt="" src="upload/'.$row["img_base_name"].'">';
}
}
else
{
echo 'File name not found in database';
}
?>

Display a default image if not exist in the database does not work as expected

I'm trying to show an default image, if an image are not stored in database. Then only show the image stored in database. How can I solve this proble? Thanks
conecta.php
<? ini_set('error_reporting',E_ALL);
ini_set('display_errors','on');
$oConni=new mysqli('localhost','****','****','****');
$oConni->set_charset('utf8');
?>
images.php
<?php
require('conecta.php');
$stmt=$oConni->prepare("SELECT IMAGEN_IMAGENES FROM IMAGENES WHERE ID_PRODUCTOS_OFERTADOS=?");
$stmt->bind_param('i',$_GET['idPrdOfr']);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($foto);
while ($stmt->fetch()) {
header('Content-Type: image/jpeg');
echo $foto;
}
?>
search.php
function pintaImagen($id_prod_ofertados){
$pintaImg=null;
require ('conecta.php');
$xSQL="SELECT IMAGEN_IMAGENES FROM IMAGENES WHERE ID_PRODUCTOS_OFERTADOS=?";
$stmt = $oConni->prepare($xSQL) or die($oConni->error);
$stmt->bind_param('i',$id_prod_ofertados);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($imagen);
while ($stmt->fetch()) {
if (isset( $imagen )){
$pintaImg.="<img class='img' src='images.php?idPrdOfr=" . $id_prod_ofertados . "' />";
}
else{
$pintaImg.="<img class='img' src='images/none.png' />";
//$pintaImg;
}
return $pintaImg;
}
}
Probably it needs to be this way:
if ($stmt->fetch() && isset( $imagen )) {
$pintaImg.="<img class='img' src='images.php?idPrdOfr=" . $id_prod_ofertados . "' />";
} else {
$pintaImg.="<img class='img' src='images/none.png' />";
//$pintaImg;
}
return $pintaImg;
instead of the while loop in search.php.

"Blog Post" show from Mysql Database wtih Image

How can I show my all "blog post" with images? Example:
Mysql table:
post_id | user_id | subject | message | image | img_name.
What is the php code to display all my posts with images in the index page? I used the following code but it doesn't display images, it shows only data. I would like to see something like this:
image | message is here
image | message is here
image | message is here
I used 3 pages
add_post.php(Html form)
add_post_process.php(process the add_post.php)
index.php (which shows my all post)
add_post_process.php:
<?php
include "db.php";
#$file = addslashes($_FILES['image']['tmp_name']);
$lastid= mysql_insert_id();
#$img = addslashes(file_get_contents($_FILES['image']['tmp_name']));
$img_name = addslashes($_FILES['image']['name']);
#$img_size = getimagesize($_FILES['image']['tmp_name']);
$upload_path = './blogpostimg/';
$post_id = addslashes($_POST['post_id']);
$user_id = addslashes($_POST['user_id']);
$subject = addslashes($_POST['subject']);
$message = addslashes($_POST['message']);
$cat_id = addslashes($_POST['cat_id']);
$cat_name = addslashes($_POST['cat_name']);
$comment_count = addslashes($_POST['comment_count']);
$ch_img = addslashes($_FILES['image']['name']);
$query = "SELECT img_name FROM blog_post WHERE img_name = '$ch_img';";
$result = mysql_query($query) or die (mysql_error());
if(isset($subject, $message))
{
$errors = array();
if(empty($subject) && empty($message) && empty($file))
{
$errors[] ='all field required';
}
else
{
if(empty($subject))
$errors[] = 'Subejct requried';
if (empty($message))
$errors[] = 'message required';
if(empty($file))
$errors[] ="SORRY, you have to be upload a image";
elseif($img_size == FALSE)
{
$errors[] ="That's not an image";
}
else
{
if(mysql_num_rows($result) != 0)
$errors[] = " You have to change this image name, already exit in our database";
}
}
if(!empty($errors))
{
foreach($errors as $error)
{
echo "<ul>";
echo "<strong><font color=red><li>$error</li></font></strong><br/>";
echo "</ul>";
}
}
else
{
if(!move_uploaded_file($_FILES['image']['tmp_name'],$upload_path . $img_name))
{
die('File Not Uploading');
}
else
{
$lastid = mysql_insert_id();
$query = mysql_query("INSERT INTO blog_post VALUES ('', '', '$subject',
'$img','$img_name','$message','$cat_id','$cat_name','',NOW() )");
if($query)
echo "Successfully uploaeded your post";
else
{
echo "Something is wrong to Upload";
}
}
}
}
?>
index.php
<?php
include "db/db.php";
$upload_path = "/secure/content/blogpostimg";
$sql= mysql_query("SELECT * FROM blog_post");
while ($rel = mysql_fetch_assoc($sql))
{
$id = $rel['post_id'];
$sub = $rel['subject'];
$imgname = $rel['img_name'];
$img = $rel ['image'];
$msg = $rel['message'];
$date = $rel['date'];
echo "<h1>". "$sub" ."</h1>". "<br/>";
echo "$imgname" ."<br/>";
echo '<img src="$upload_path " />';
echo "$msg" . "<br/>";
echo "$date" . "<br/>";
echo "<hr/>";
echo "<br/>";
}
?>
The mysql table structure is
post_id(int)
User_id(int)
subject(varchar)
image(blob)
img_name(varchar)
message(text)
change
echo '<img src="$upload_path " />';
to
echo '<img src="' . $upload_path . '/' . $img . '" />';
that should do the trick..
I don't now if it matters in performanceways.. but howcome you use blob instead of a varchar.. 255 characters for a filename should be enough.
In your index.php you have <img src="$upload_path" />. Instead of $upload_path, src needs to be the URL to your image.
I just noticed that you are storing the image itself in the database. There is no need to do this if you move it to a publicly accessible directory, e.g. /var/www/images/myimage.jpg

Categories