I have an issue rendering stored images from phpmyadmin database.
I have two files, first one is image.php ,which is suppose to retrieve the images from database :
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
$conn = mysqli_connect("hostname","username","password");
if(!$conn)
{
echo mysql_error();
}
$db = mysqli_select_db("imagestore");
if(!$db)
{
echo mysql_error();
}
$ano = $_GET['ano'];
$q = "SELECT aphoto,aphototype FROM animaldata where ano='$ano'";
$r = mysqli_query("$q",$conn);
if($r)
{
$row = mysqli_fetch_array($r);
$type = "Content-type: ".$row['aphototype'];
header($type);
readfile($ano);
echo mysql_real_escape_string.$row['aphoto'];
}
else
{
echo mysql_error();
}
?>
and show.php , which is suppose to show the retrieved image :
<?php
//show information
ini_set('display_errors',1);
error_reporting(E_ALL);
include "connect.php";
$q = "SELECT * FROM animaldata";
$r = mysqli_query($conn,$q);
if($r)
{
while($row=mysqli_fetch_array($r))
{
//header("Content-type: text/html");
echo "</br>";
echo $row['aname'];
echo "</br>";
echo $row['adetails'];
echo "</br>";
//$type = "Content-type: ".$row['aphototype'];
//header($type);
echo "<img src=image.php?ano=".$row['ano']." width=300 height=100/>";
}
}
else
{
echo mysql_error();
}
?>
When I try show.php i get this result:
I would be very grateful for any help, because i tried many different codes but i could not find the solution and still getting the same result.
Thank you.
You should get rid of the readfileline as it is not needed and also the mysqli_real_escape_string from the line below. Otherwise this looks like it could work, but without knowing how you stored the images I can't know for sure. For example, if you stored them base64 encoded then you'd need to echo the the base64 decoded string.
Related
It's not a duplicate question about UTF-8 Unicode.
I am new to php and I am trying to create a json response.
I added data into my database properly as follows.
Then I tried to connect to DB and i did it successfully .
but after that when I tried to create a json response by using the following code, it doesn't shows any json response .
My PHP code is :
<?php
define('HOST','localhost');
define('USER','root');
define('PASS','qwerty');
define('DB','carol');
$con = mysqli_connect(HOST,USER,PASS,DB);
if (!$con)
{
echo "Please try later..";
}
else
{
echo "DB Connected..";
}
$sql = "SELECT * from songs";
$res = mysqli_query($con,$sql);
if (!$res)
{
echo "query failed..";
}
else
{
echo "Query success..";
echo (mysqli_num_rows($res));
}
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result,
array('title'=>$row[0]),
array('url'=>$row[1]),
array('lyrics'=>$row[2])
);
}
echo json_encode(array("result"=>$result));
mysqli_close($con);
?>
I'm getting only echo of DB Connected , Query Success and 14 (no of rows)
I'm trying PHP for the first time by using some online tutuorials.
if I did any mistake in my code,please help me to find my mistake.
Thank you in advance.
After I added echo var_dump($res);
I got
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" />';
}
I am going out of my mind as it is. I am trying to pass a variable from a page that shows all albums thumbnail image and name to a page that will display all the pictures in that gallery using that passed variable, but the variable is empty in the url on the target page. I have seen similar cases on the web and on this site and I've applied the suggestions but it's still the same. Here is the code that lists the thumbnail and passes the variable(id).
<?php
include ("config.php");
$conn = mysqli_connect(DB_DSN,DB_USERNAME,DB_PASSWORD,dbname);
$albums = mysqli_query($conn,"SELECT * FROM albums");
if (mysqli_num_rows($albums) == 0) {
echo "You have no album to display. Please upload an album using the form above to get started. ";
}
else{
echo "Albums created so far:<br><br>";
echo "<table rows = '4'><tr>";
while ($thumb = mysqli_fetch_array($albums)) {
echo '<td><a href ="view.php?id="'.$thumb['id'].'"/><img src = "'.$thumb['thumbnail'].'"/><br>'.$thumb['album_name'].'<br>'.$thumb['id'].'</a></td>';
}
echo "</tr></table>";
}
?>
The code for getting the passed variable is as follows:
<?php
include("config.php");
$conn = mysqli_connect(DB_DSN,DB_USERNAME,DB_PASSWORD);
$db = mysqli_select_db($conn,dbname);
if (isset($_GET['id'])) {
$album_id = $_GET['id'];
$pic = "SELECT * FROM photos WHERE album_id ='$album_id'";
$picQuery = mysqli_query($conn,$pic);
if (!$picQuery) {
exit();
}
if (mysqli_num_rows($picQuery) == 0) {
echo "Sorry, no Pictures to display for this album";
}
else{
echo "Pictures in the gallery:<br><br>";
while ($result = mysqli_fetch_assoc($picQuery)) {
echo "<img src='".$result['photo_path']."'/>";
}
}
}
?>
Please help as i have spent the last two days trying to get it right.
First, your's code is weak against sql injections:
$album_id = $_GET['id']; // here
$pic = "SELECT * FROM photos WHERE album_id ='$album_id'";
Use either $album_id = intval($_GET['id']) or prepared statements functionality.
Second, add debug lines to your code, like:
<?php
include("config.php");
if (isset($_GET['id'])) {
$album_id = intval($_GET['id']);
var_dump($album_id); // should print actual passed id
$conn = mysqli_connect(DB_DSN,DB_USERNAME,DB_PASSWORD);
var_dump($conn _id); // should print conn resource value
$db = mysqli_select_db($conn, dbname);
var_dump($db); // should print 'true' if db select is ok
$pic = "SELECT * FROM photos WHERE album_id ='$album_id'";
$picQuery = mysqli_query($conn, $pic);
var_dump($picQuery); // should print query resource value
if (!$picQuery) {
exit();
}
if (mysqli_num_rows($picQuery) == 0) {
echo "Sorry, no Pictures to display for this album";
} else {
echo "Pictures in the gallery:<br><br>";
while (($result = mysqli_fetch_assoc($picQuery)) !== false) {
var_dump($result ); // should print fetched assoc array
echo "<img src='".$result['photo_path']."'/>";
}
}
}
Notice $album_id = intval($_GET['id']) and while (($result = mysqli_fetch_assoc($picQuery)) !== false) parts
Then follow link view.php?id=<existing-album-id> and observe debug result. On which step debug output differs from expected - there problem is.
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!";
}
im having a problem with my code in uploading and displaying images.. well I am planning to redirect the page after the upload process is done so I used a header function but gave warning and errors and unfortunately failed the upload.. how can I remove it? here's the code..
<?php
//connect to the database//
$con = mysql_connect("localhost","root", "");
if(!$con)
{
die('Could not connect to the database:' . mysql_error());
echo "ERROR IN CONNECTION";
}
$sel = mysql_select_db("imagedatabase");
if(!$sel)
{
die('Could not connect to the database:' . mysql_error());
echo "ERROR IN CONNECTION";
}
//file properties//
$file = $_FILES['image']['tmp_name'];
echo '<br />';
/*if(!isset($file))
echo "Please select your images";
else
{
*/for($count = 0; $count < count($_FILES['image']); $count++)
{
//$image = file_get_contents($_FILES['image']['tmp_name']);
$image_desc[$count] = addslashes($_POST['imageDescription'][$count]);
$image_name[$count] = addslashes($_FILES['image]']['name'][$count]); echo '<br \>';
$image_size[$count] = #getimagesize($_FILES['image']['tmp_name'][$count]);
$error[$count] = $_FILES['image']['error'][$count];
if($image_size[$count] === FALSE || ($image_size[$count]) == 0)
echo "That's not an image";
else
{
// Temporary file name stored on the server
$tmpName[$count] = $_FILES['image']['tmp_name'][$count];
// Read the file
$fp[$count] = fopen($tmpName[$count], 'r');
$data[$count] = fread($fp[$count], filesize($tmpName[$count]));
$data[$count] = addslashes($data[$count]);
fclose($fp[$count]);
// Create the query and insert
// into our database.
$results = mysql_query("INSERT INTO images( description, image) VALUES ('$image_desc[$count]','$data[$count]')", $con);
if(!$results)
echo "Problem uploding the image. Please check your database";
//else
//{
echo "";
//$last_id = mysql_insert_id();
//echo "Image Uploaded. <p /> <p /><img src=display.php? id=$last_id>";
//header('Lcation: display2.php?id=$last_id');
}
//}
}
mysql_close($con);
header('Location: fGallery.php');
?>
the header function supposedly directs me to another page that would make a gallery.. here is the code..
<?php
//connect to the database//
mysql_connect("localhost","root", "") or die(mysql_error());
mysql_select_db("imagedatabase") or die(mysql_error());
//requesting image id
$image = mysql_query("SELECT * FROM images ORDER BY id DESC");
while($row = mysql_fetch_assoc($image))
{
foreach ($row as $img) echo '<img src="img.php?id='.$img["id"].'">';
}
mysql_close();
?>
I have also a problem with my gallery .. some help will be GREAT! THANKS! :D
The header() function must be called before any other echo or die calls which produce output.
You may could buffer your outputs if you need the output, but in your case it makes no difference because the output will never be shown to the user. The browser will read the redirect and navigate to the second page.
<?php
//connect to the database//
$con = mysql_connect("localhost","root", "");
if(!$con) {
// this output is okay the redirect will never be reached.
die('Could not connect to the database:' . mysql_error());
// remember after a die this message will never be shown!
echo "ERROR IN CONNECTION";
}
$sel = mysql_select_db("imagedatabase");
if(!$sel) {
die('Could not connect to the database:' . mysql_error());
echo "ERROR IN CONNECTION"; // same here with the die!
}
//file properties//
$file = $_FILES['image']['tmp_name'];
// OUTPUT
// echo '<br />';
// removed out commented code
for($count = 0; $count < count($_FILES['image']); $count++)
{
$image_desc[$count] = addslashes($_POST['imageDescription'][$count]);
$image_name[$count] = addslashes($_FILES['image]']['name'][$count]);
// OUTPUT
// echo '<br \>';
$image_size[$count] = #getimagesize($_FILES['image']['tmp_name'][$count]);
$error[$count] = $_FILES['image']['error'][$count];
if($image_size[$count] === FALSE || ($image_size[$count]) == 0)
// you may better use a die if you want to prevent the redirection
echo "That's not an image";
else
{
// Temporary file name stored on the server
$tmpName[$count] = $_FILES['image']['tmp_name'][$count];
// Read the file
$fp[$count] = fopen($tmpName[$count], 'r');
$data[$count] = fread($fp[$count], filesize($tmpName[$count]));
$data[$count] = addslashes($data[$count]);
fclose($fp[$count]);
// Create the query and insert
// into our database.
$results = mysql_query("INSERT INTO images( description, image) VALUES ('$image_desc[$count]','$data[$count]')", $con);
if(!$results) // use die
echo "Problem uploding the image. Please check your database";
// OUTPUT
// echo "";
}
}
mysql_close($con);
header('Location: fGallery.php');
?>
Above I marked every output for you and also removed all outcomments lines.
You've got a header error because you printed out <br /> before the header function. In order to use the header function you can't print out any information before it. That's why you're getting the error.
Regarding your gallery the foreach loop is unnecessary. You can change the code to this:
while($row = mysql_fetch_assoc($image)) {
echo '<img src="img.php?id='.$row["id"].'">';
}
You can use ob_start() to get data in buffer.