hello i wanted to display the nultiple image in the webpage from mysql database. I am new to php. till now it only displays one image at a time. Please help .

Here is the code snippet:

<?php
	$db = mysqli_connect ('localhost', 'username', 'pwd', 'databasename');
	
	$query = "select * from picture";
	$result = mysqli_query($db, $query);
	$row_cnt = mysqli_num_rows($result);
	for($i=0; $i<$row_cnt; $i++)
	{
		$row = mysqli_fetch_assoc($result);
		header ('Content-Type: '.$row['type']);
		echo $row['pic'];
	}
	mysqli_free_result($result);
?>
Member Avatar for diafol

Ok couple of things,

we usually use while() loop to loop through a mysql/i object not a for.

the fact that you've set content type of the page along with content. FULL STOP. THAT's it. No more output.

Is your image data stored as blob in the DB?

If using this method, you need an external file to create the image and loop over that using a querystring:

while(...){
  echo "<img src=\"makeimg.php?id={$row['id']}\" />";
}

the makeimg.php file makes the img:

//get data from DB using $_GET['id'] as the id
//assume these vars in $row array.
header ("Content-Type: {$row['type']}");
echo $row['pic'];

Ok couple of things,

we usually use while() loop to loop through a mysql/i object not a for.

the fact that you've set content type of the page along with content. FULL STOP. THAT's it. No more output.

Is your image data stored as blob in the DB?

If using this method, you need an external file to create the image and loop over that using a querystring:

while(...){
  echo "<img src=\"makeimg.php?id={$row['id']}\" />";
}

the makeimg.php file makes the img:

//get data from DB using $_GET['id'] as the id
//assume these vars in $row array.
header ("Content-Type: {$row['type']}");
echo $row['pic'];

Hello ardav,
Thanks for the quick reply

This is my picturetest.php file:

<?php
	$db = mysqli_connect ('localhost', 'username', 'pwd', 'database');
	
	$query = "select * from picture";
	$result = mysqli_query($db, $query);
	$row_cnt = mysqli_num_rows($result);
	$i=0;
	while($i<$row_cnt)
	{
		$row = mysqli_fetch_assoc($result);
		echo "<img src=\"makeimg.php?id={$row['id']}\" />";
		$i++;
	}	
	
	mysqli_free_result($result);
?>

and this my makeimage.php file

<?php
$db = mysqli_connect ('localhost', 'username', 'pwd', 'database');

$result = mysql_query('SELECT * FROM picture WHERE id = ' . (int)$_GET['id']);
$row = mysqli_fetch_row($result);
header ("Content-Type: {$row['type']}");
echo $row['pic'];
?>

I don't know whats wrong with it, when i run testpicture.php image doesn't appear an di am using the blob to store the image in db. Please excuse me with my dump questions as I am new in this field.

Member Avatar for diafol

dunno, try:

if(mysqli_num_rows($result)>0){
        echo "ok";
	while($row = mysqli_fetch_assoc($result)){
	   echo "<img src=\"makeimg.php?id={$row['id']}\" />";
	}	
}else{
        echo "no images";
}

Hi ardav,
I don't know whats wrong but its not working. The picture doesn't appear though it displays the ok and three picture like scratch.(inserted 3 images in db)

when i ran the makeimage.php it showed me this error:

Undefined index: id
mysqli_fetch_row() expects parameter 1 to be mysqli_result, boolean given

Would really appreciate your help. Thanks

Line 4 in makeimage.php should be mysqli_query , instead of mysql_query . You cannot mix the mysql and mysqli modules like that.

this is my picturetest2.php

<?php
    $db = mysqli_connect ('localhost', '---', '--', '--');

    $query = "select * from picture ";
    $result = mysqli_query($db, $query);
    $row_cnt = mysqli_num_rows($result);

    if(mysqli_num_rows($result)>0)
    {
        echo "ok";
        while($row = mysqli_fetch_assoc($result))
        {

            echo "<img src=\"makeimage.php?id={$row['id']}\" />";

        }   
    }
    else 
    {
        echo "no images";
    }
    mysqli_free_result($result);
?>

which gives in the result: ok and three scratch picture (X X X)

this is my makeimage.php

<?php
$db = mysqli_connect ('localhost', '...', '........', '.....');
$query = "SELECT * FROM picture WHERE id = ".(int)$_GET['id'];
$result = mysqli_query($db, $query);
$row = mysqli_fetch_row($result);
header ("Content-Type: {$row['type']}");
echo $row['pic'];
?>

which gives me error:

Undefined index: id on line 3

That is a notice, not an error. It means that the url did not contain ?id=<X>
The query will fail in that case. You can do this to remove the notice:

$query = 'SELECT * FROM picture WHERE id = ' . (int)(isset($_GET['id']) ? $_GET['id'] : 0);

(Use code tags around your code)

Thanks for the quick response but still the pictures donot display!!! only the notice deosn't appear. help please

hello

here is my picturetest2.php

<?php
	$db = mysqli_connect ('localhost', '..', '..', '...');
	
	$query = "select * from picture ";
	$result = mysqli_query($db, $query);
	$row_cnt = mysqli_num_rows($result);
	
	if(mysqli_num_rows($result)>0)
	{
		echo "ok";
		while($row = mysqli_fetch_assoc($result))
		{
		
			echo "<img src=\"makeimage.php?id={$row['id']}\" />";
			echo "<br/>";
			echo "<br/>";
			
		}	
	}
	else 
	{
		echo "no images";
	}
	mysqli_free_result($result);
?>

and makeimage.php

<?php
$db = mysqli_connect ('localhost', '...', '....', '....');
$query = "SELECT * FROM picture WHERE id = ".(int)(isset($_GET['id']) ? $_GET['id'] : 0);
$result = mysqli_query($db, $query);
$row = mysqli_fetch_row($result);
header ("Content-Type:". $row['type']);
echo $row['pic'];
?>

It doesn't display the images only the scratch image (X)

Help please....would really appreciate your help

Member Avatar for diafol

OK, run the makeimage.php in the address bar - forget the first page for now.

Also comment out the header() command with //.

Now try to identify what's being passed by echoing the $query.

Also find out if image tags are being written properly in html. Go to 'view source' or whatever it's called in your browser and check out picturetest2.php :

do you have links like this:

<img src="makeimage.php?id=3" />
<img src="makeimage.php?id=7" />
<img src="makeimage.php?id=9" />

or the links that you expect to see.

hello,
I have these links :

<img src="makeimage.php?id=1" /><br/><br/><img src="makeimage.php?id=2" /><br/><br/><img src="makeimage.php?id=3" /><br/><br/>

But when i echo the query (

$query = "SELECT * FROM picture WHERE id = ".(int)(isset($_GET['id']) ? $_GET['id'] : 0);

) it shows me these result:

SELECT * FROM picture WHERE id = 0

id should be 1 right? but it is showing 0

Thanks

Member Avatar for diafol

Yes, great! That answers the question. It means that the querystring isn't getting passed properly for some reason.

To show that it should work (proof of concept):

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<img src="imggen.php?id=4" />
</body>
</html>

imggen.php:

<?php
if(isset($_GET['id']) && $_GET['id'] == 4){
  header('Content-Type: image/jpeg');
  $blob = file_get_contents("img/banks1.jpg");
  echo $blob;
}
?>

all works fine for me. SO, perhaps simplifying...

<?php
$img = file_get_contents("defaultimage.jpg");
$contenttype = "image/jpeg";
//those are the defaults just in case img not found - e.g. error image

if(isset($_GET['id'] && is_int($_GET['id'])){
  $db = mysqli_connect ('localhost', '...', '....', '....');
  $imgid = $_GET['id']; //no need to mysql_real_escape_string as it is an integer  
  $result = mysqli_query($db, "SELECT * FROM picture WHERE id = $imgid");
  //you should check for an exisiting record here with mysqli_num_rows()
  $row = mysqli_fetch_row($result);
  $img = $row['pic']; 
  $contenttype = $row['type'];
}
header ("Content-Type: $contenttype");
echo $img;  
?>

Even though you've worked this as a blob, I can't help thinking that it's easier to store image paths in the DB and just use the paths in your <img> tags.

hello,
I followed your code for displaying the default image if the image is not found then it only displays the default image. so how to fix the error. I mean $_GET only shows the 0 instead of 1 and other. So do you have any idea on how to fix this?
What's the cause of the problem?
Thanks

Member Avatar for diafol

OK run my code again but directly from the address bar:

makeimage.php?id=3

etc.

see what happens

I can't see why the id isn't recognised.

Try this:

if (isset($_GET['id'])) {
$id = $_GET['id'];
}
else {
$id = "0";
}

$dbc = mysqli_connect('host', 'user', 'pass', 'dbname');
$query = "SELECT * FROM picture WHERE id = '" . $id . "';
$result = mysqli_query($dbc, $query);
while($row = mysqli_fetch_array($result)) {

echo "<img src='" . $row['image'] . "' />"; //just put the path to the image into the database

}
mysqli_close($dbc);

Hello ardav,

I ran your code:

picturetest2.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Untitled Document</title>
    </head>
    <body>
    <img src="makeimage.php?id=3" />
    </body>
    </html>

and makeimage.php

if(isset($_GET['id']) && $_GET['id'] == 3){
    header('Content-Type: image/jpeg');
    $blob = file_get_contents("3.jpg");
    echo $blob;
    }

It showed me the picture 3.jpg, is that what you mean by running the code directly from address bar? But the problem is to read the id through the query and its not recognizing the id. Just to confirm storing the image through blob is done in this way right-> insert into pictures value (.....,'image/jpeg',LOAD_FILE('c://....');

Member Avatar for diafol

THis is taken from the MySQL manual about LOAD_FILE (http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_load-file):

Reads the file and returns the file contents as a string. To use this function, the file must be located on the server host, you must specify the full path name to the file, and you must have the FILE privilege. The file must be readable by all and its size less than max_allowed_packet bytes. If the secure_file_priv system variable is set to a nonempty directory name, the file to be loaded must be located in that directory.

If the file does not exist or cannot be read because one of the preceding conditions is not satisfied, the function returns NULL.

Is there any data in your blob field?

I have to say I almost never use blob, I store the file location (path) and store the images in an 'images' directory.

my table creation and insertion is as follows:

Create table .....(int id, varchar type, longblob pic);
insert into ... values(1, image/jpeg, LOAD_FILE('c://../.../1.jpg'));

so there is data in the blob field right? any idea to fix the error?
thanks

Member Avatar for diafol
insert into ... values(1, image/jpeg, LOAD_FILE('c://../.../1.jpg'));

doesn't look quite right to me.

image/jpeg should have quotes around it.

I thought LOAD_FILE files needed to be on the server. Are they? They look local.

Also, do you really need to apply an id manually?
How about this:

Where $content is the content of the file (by file_get_contents).

"INSERT INTO table SET id = 1, `type` = 'image/jpeg', longblob = '$content';"

ya LOAD_FILE files is in the server.
It's like this

insert into ... values (1,'image/jpeg',LOAD_FILE('c://xampp/htdocs/../1.jpg'));
Member Avatar for diafol

OK, should work:

$r = mysql_query("INSERT INTO table SET type = 'image/jpeg',pic = LOAD_FILE('c://xampp/htdocs/1.jpg')");

Works for me.

Mind you I think we've gone right off track, it's the 'id' that we can't retrieve from the url.

so what's the solution to the problem?

$r = mysql_query("INSERT INTO table SET type = 'image/jpeg',pic = LOAD_FILE('c://xampp/htdocs/1.jpg')");

the above code is just the way of inserting the data to mysql which i have done it in command line in mysql but y u din't put the id over there? and what's the way to display images in webpage(php)? Help needed!!!!!!!!

Member Avatar for diafol

The ID should be a Primary Key field and set to autoincrement (integer).
Therefore you don't explicitly state the id, it is done for you automatically. Therefore, the query you posted should work fine.

Member Avatar for diafol

@ChrisHardwick

This is being implemented:

<img src="makeimage.php?id=1" />

Or are you suggesting something different?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.