Hello!

I have more or less zero knowledge about coding in PHP. The most I've done is includes, to help me maintaining my sites more efficiently. I hope I will not offend anyone with this question.

Anyhow, towards my issue.

I have one table containing several fields, with information such as ID, name, brand, year, measurements, thumbnail, etc.
I already have a simple-looking script that I found which pulls out the information from entries and displays it through a template, but what troubles me is this:
Each entry I have comes with images.
First it's the item's thumbnail, which URL I would put into the thumb field and then display.
Secondly, I want to display separate images of the different colors of said item. Blue, red, green, etc.

And this is where my main issue comes up. How do you most efficiently display many images stored in one entry?

Do I have to add a new field for each color, and add the URL, or is there any better ways? Also, not all entries might have an entry for the color green, nor the same amount of colors. Some items might have 5 colors, and other entries may have 10 different variations.
I also need a field which displays more images of the item. These may also differ in the amount of images.
I really have no idea how to go about this issue.

It'd be really nice if there were a way that'd make adding and displaying images more easy. Sort of like when you upload images through the FTP, and the code would just pull out the existing images in the folder?

I hope this post wasn't too confusing. Thanks in advance to anyone who'd be kind enough to help me out.

- Linda

Recommended Answers

All 22 Replies

Well, it is confusing (at least for me it is). If I understand it correctly the images are not stored in the database, only the url pointing to were the image is is stored.
And if I understand the following also, you are able to display this image. Now for the really confusing bit, the red, green and blue images. Where do they come from? And what determines how many of these images there are?

Yeah, only the URL. That's how the script was set up.

Let's say I want to add the info of two lamps. Lamp A only comes in green and yellow versions, and Lamp B comes in green, blue, red and purple. The amount is determined by the actual item I'm adding, so. It's different each time, mostly. Did that make more sense?

Because I don't know anything about how you want the images to appear on your website, I tried to keep it simple with the following code.
First, you open the database do the query and display the text part (id, name, etc). You have url's in your database so to display the first image is easy (line 15 in the code).
$models tells you how many different colors there are and so how many images to display. The loop starting at line 17 will take care of that.

For example the url in your database is: "http://www.somewhere.com/images/lampA.jpg". Line 15 will display this image. Line 18 will display the image "http://www.somewhere.com/images/lampA1.jpg" and if there are any more lampA2.jpg, lampA3.jpg and so on.

It means that your images must follow the following rule, it can have almost any name, but before the extensions (.jpg or .png) there has to be a number, except for the first one.

Hope this will help you...

<?php
open_database(); // function to open the correct database

$result=mysql_query("select * from $tbl_name");
while($row=mysql_fetch_assoc($result)){

	$id = $row['id'];
	$name = $row['name'];
	$thumb = $row['thumbnail'];		// the url to your base image
	$models = $row['models'];		// how many colors are there

	$path_parts = pathinfo($thumb);		// split the url into its different parts

	display_data();				// function to display id, name ....
	echo "<img src=\"".$thumb."\"/>";	// display first image
	
	for ($i=0; $i < $models; $i++) {
		echo "<img src=\"".$path_parts['dirname']."/".
                           $path_parts['filename'].$i.".".
                           $path_parts['extension']."\"/>";
	}
}

close_database() // function to close and cleanup
?>

Well this is a very confusing thread.

Can you please be a little more specific as to what you are asking?

Do you have a mysql database?

Are you trying to use a search so you search for 'blue lamp'
and it will bring up all items with blue && lamp in the keywords, but not those lamps that dont come in blue?

or simply display a table of images where the user clicks on it and a bigger image or info whatever pops up

Because I don't know anything about how you want the images to appear on your website, I tried to keep it simple with the following code.
First, you open the database do the query and display the text part (id, name, etc). You have url's in your database so to display the first image is easy (line 15 in the code).
$models tells you how many different colors there are and so how many images to display. The loop starting at line 17 will take care of that.

For example the url in your database is: "http://www.somewhere.com/images/lampA.jpg". Line 15 will display this image. Line 18 will display the image "http://www.somewhere.com/images/lampA1.jpg" and if there are any more lampA2.jpg, lampA3.jpg and so on.

It means that your images must follow the following rule, it can have almost any name, but before the extensions (.jpg or .png) there has to be a number, except for the first one.

Hope this will help you...

While this looks like what I was after (thank you), I have to admit I can't manage to get anything else but a blank page. So I assume I'm doing something wrong. In the parts that are related to the $path_parts... am I supposed to edit something in the code, or the actual database, or perhaps not at all? It's a bit confusing.

While this looks like what I was after (thank you), I have to admit I can't manage to get anything else but a blank page. So I assume I'm doing something wrong. In the parts that are related to the $path_parts... am I supposed to edit something in the code, or the actual database, or perhaps not at all? It's a bit confusing.

You must not take my code as it is. I think (pretty sure) that you don't have the functions "open_database, display_data and close_database".
Other than that, the code will work. In your php code look for the part where a query is being done. It will look like line 4 of my code. Just after that part there has to be some code that does something with the result of the query. Maybe you can copy that part and post it here.
In this part you have to make changes. But were exactly and what, well I have no clue yet. Just after the first image is displayed insert the path_parts bit and the for.... loop.
And, in your database there has to be a field models with the number of color models available.
As you don't have any php programming experience, it is probably better to post the original code here so we can have a look at it.

It's probably best if I gave you the entire thing.

First this is the part of the script that'd call on the info from the database and list the items thumbnails. Just like a gallery, since that's the way I wanted to display it.

<?php

$hostname='localhost'; 
$user='username'; 
$pass='password'; 
$dbase='database'; 

$connection = mysql_connect("$hostname" , "$user" , "$pass") or die ("Can't connect to MySQL");
$db = mysql_select_db($dbase , $connection) or die ("Can't select database.");

$q = "select * from wardrobe order by id desc"; 
$result= mysql_query($q, $connection) or die
("Could not execute query : $q." . mysql_error());

$rows_per_page=36; 
$total_records=mysql_num_rows($result);
$pages = ceil($total_records / $rows_per_page);
$screen = $_GET["screen"];
if (!isset($screen))
$screen=0;
$start = $screen * $rows_per_page;
$q .= "LIMIT $start, $rows_per_page";
$result= mysql_query($q, $connection) or die
("Could not execute query : $q." . mysql_error());

//Display data from table
while ($row=mysql_fetch_array($result))
{
$id=$row["id"];
$year=$row["year"];
$thumb=$row["thumb"];

?>

<a  href="http://domain.com/folder/<?php echo "$id"; ?>"><img src="http://domain.com/folder/<?php echo "$thumb"; ?>" alt="" /></a>

And when clicking an item's thumbnail, you'd be referred (through htaccess url rewrite) to this other page with the PHP code that gathers the db info to display the item:

<?php

$hostname='localhost'; 
$user='username'; 
$pass='password'; 
$dbase='database'; 

$connection = mysql_connect("$hostname" , "$user" , "$pass") or die ("Can't connect to MySQL");
$db = mysql_select_db($dbase , $connection) or die ("Can't select database."); 
$id = $_GET['id'];

$q="SELECT * from wardrobe where id='$id'"; 
$result= mysql_query($q) or die
("Could not execute query : $q." . mysql_error());

while ($row=mysql_fetch_array($result))
{
$id=$row["id"];
$year=$row["year"];
$thumb=$row["thumb"];
$engname=$row["engname"];
$japname=$row["japname"];
$brand=$row["brand"];
$price=$row["price"];
$colors=$row["colors"];
$size=$row["size"];
$angles=$row["angles"];

}

include("preview.php");

?>

The preview.php is a HTML/CSS template where the actual output would be displayed. To get the images to display I'd use a normal IMG tag in the template page, like this:

<img src="http://domain.com/folder/<?php echo "$thumb"; ?>" class="border" alt="" />

And, that's about it. I figured the open_database and close_database had to be edited, but I wasn't sure about the display_data. This script works fine for downloads, or single images, but I realized it doesn't work well if you need to add more images than that, heh. So if I could implement the sort of function your script seem to provide, it'd save me a lot of time and pain. :)

Thank you for the code and explanation. Where I live it is midnight now, so will look at it tomorrow (local time).

In the second php script there is a while loop. Does this mean that the query

$q="SELECT * from wardrobe where id='$id'";

can have more than one result?
In other words, id is not unique?

It looks like the while loop is not needed (if there is always only one result). If so, the changes must be made in preview.php and are minor. Just a few loops. But if there are more results ... it start to get confusing again:?:

In the second php script and only if id = unique, just make the following changes (line 14~21) and remove the while loop:

$q="SELECT * from wardrobe where id='$id'";
$result= mysql_query($q) or die ("Could not execute query : $q." . mysql_error());
$row=mysql_fetch_array($result));

$id=$row["id"];
$year=$row["year"];
$thumb=$row["thumb"];
$engname=$row["engname"];
$japname=$row["japname"];
$brand=$row["brand"];
$price=$row["price"];
$colors=$row["colors"];

// The next lines create an array to store the filenames of all the images with another color.
// for example is $thumb = "lampA.jpg" then $images[0] will be "lampA1.jpg" and so on.
// the total number of elements in the array is determined by the number or colors aviable
// that is, if $colors is a number indicating the number of different colors.
$images = array();
for ($i=1; $i < $colors; $i++) {
	$path_parts = pathinfo($thumb);
	$images[] = $path_parts['filename'].$i.".".$path_parts['extension'];
}

$size=$row["size"];
$angles=$row["angles"];

And in preview.php insert:

<img src="http://domain.com/folder/<?php echo "$thumb"; ?>" class="border" alt="" />
<?php
foreach ($images as $image) {
	echo "<img src=\"http://domain.com/folder/".$image."\" class=\"border\" alt=\"\" />";
?>

That should do it ... (unless, well you now there are so many things that can go wrong).

In the second php script and only if id = unique, just make the following changes (line 14~21) and remove the while loop:

$q="SELECT * from wardrobe where id='$id'";
$result= mysql_query($q) or die ("Could not execute query : $q." . mysql_error());
$row=mysql_fetch_array($result));

$id=$row["id"];
$year=$row["year"];
$thumb=$row["thumb"];
$engname=$row["engname"];
$japname=$row["japname"];
$brand=$row["brand"];
$price=$row["price"];
$colors=$row["colors"];

// The next lines create an array to store the filenames of all the images with another color.
// for example is $thumb = "lampA.jpg" then $images[0] will be "lampA1.jpg" and so on.
// the total number of elements in the array is determined by the number or colors aviable
// that is, if $colors is a number indicating the number of different colors.
$images = array();
for ($i=1; $i < $colors; $i++) {
	$path_parts = pathinfo($thumb);
	$images[] = $path_parts['filename'].$i.".".$path_parts['extension'];
}

$size=$row["size"];
$angles=$row["angles"];

And in preview.php insert:

<img src="http://domain.com/folder/<?php echo "$thumb"; ?>" class="border" alt="" />
<?php
foreach ($images as $image) {
	echo "<img src=\"http://domain.com/folder/".$image."\" class=\"border\" alt=\"\" />";
?>

That should do it ... (unless, well you now there are so many things that can go wrong).

Well ID's should be unique since it's a primary key? Anyhow, that code is still giving me a blank page so I guess something did indeed go wrong somewhere. Uhm also, if we get this working, is it possible to apply the same thing twice? Since I need the same sort of concept once for colors and then for additional images.

Well ID's should be unique since it's a primary key? Anyhow, that code is still giving me a blank page so I guess something did indeed go wrong somewhere. Uhm also, if we get this working, is it possible to apply the same thing twice? Since I need the same sort of concept once for colors and then for additional images.

Let's try to solve the problem. I did create a database and stored 4 images in a folder on my server. To keep it simple, the database only contains the necessary part needed for the images. If you place the code below on a webserver and open it with a browser, you will get 4 images of lamps on the screen. The database only has knowledge about 1 lamp. You can also go here: http://argumentum.colhome.net/dimages/ to see the script in action.
The code used here, is a slightly modified version of your second php script. (removed the not needed fields and id=1). Preview.php is gone here, the code to display the images are the last lines.
Hope this will bring you further.

<?php
$hostname='colhome.net';
$user='daniweb';
$pass='daniweb';
$dbase='daniweb';

// This database has the following fields: id (integer), thumb (varchar60) and colors (integer)
// It currently contains the following data: 1, lamp.jpg, 4

$connection = mysql_connect("$hostname" , "$user" , "$pass") or die ("Can't connect to MySQL");
$db = mysql_select_db($dbase , $connection) or die ("Can't select database.");

$id = 1;

$q="SELECT * from wardrobe where id='$id'";
$result= mysql_query($q) or die ("Could not execute query : $q." . mysql_error());
$row=mysql_fetch_array($result);

$id=$row["id"];
$thumb=$row["thumb"];
$colors=$row["colors"];

$images = array();
for ($i=1; $i < $colors; $i++) {
	$path_parts = pathinfo($thumb);
	$images[] = $path_parts['filename'].$i.".".$path_parts['extension'];
}

echo "<img src=\"http://argumentum.colhome.net/dimages/".$thumb."\" width=\"150px\"/>";
foreach ($images as $image) {
	echo "<img src=\"http://argumentum.colhome.net/dimages/".$image."\" width=\"150px\"/>";
}
?>

have you tried it with a session?
eg add:

<?php
if (!isset($_SESSION)) {
  session_start();
}
//rest of code

this may solve your blank page problem

The blank page problem has nothing to do with setting a session. It has however everything to do with errors in the previous php code.

sorry too many errors.
will fix soon

Thank you very very much, Colweb. That seems to work fine. I'm very grateful for you taking your time to help me. This will save me many hours of work! :)

Thank you Metalix for trying to help me out as well.

You're great guys! :)

Actually, I seem to run into this one odd thing: I can't place my images in subfolders. It'll print i.e. folder/folder/LampA.jpg properly, but it'll ignore the folders (which I specified in the db) when it keeps printing LampA1.jpg, LampA2.jpg, etc.

Is there a way to solve this?

Actually, I seem to run into this one odd thing: I can't place my images in subfolders. It'll print i.e. folder/folder/LampA.jpg properly, but it'll ignore the folders (which I specified in the db) when it keeps printing LampA1.jpg, LampA2.jpg, etc.

Is there a way to solve this?

If you have the following in your database: "folder/folder/LampA.jpg" all you need to do is change line 26 in my last code from

$images[] = $path_parts['filename'].$i.".".$path_parts['extension'];

to

$images[] = $path_parts['dirname']."/".$path_parts['filename'].$i.".".$path_parts['extension'];

If you have the following in your database: "folder/folder/LampA.jpg" all you need to do is change line 26 in my last code from

$images[] = $path_parts['filename'].$i.".".$path_parts['extension'];

to

$images[] = $path_parts['dirname']."/".$path_parts['filename'].$i.".".$path_parts['extension'];

Thank you so much! That worked great. Uhm, if I dare to ask one more thing... Is there a way to insert a <br /> tag after every X entries displayed, so it doesn't turn into one long huge row of images? I tried to search for it, but I mostly got hits on pagination, which isn't what I wanted. :/ Is it achieved by an if else statement?

Thank you so much! That worked great. Uhm, if I dare to ask one more thing... Is there a way to insert a <br /> tag after every X entries displayed, so it doesn't turn into one long huge row of images? I tried to search for it, but I mostly got hits on pagination, which isn't what I wanted. :/ Is it achieved by an if else statement?

A break <br> after a certain number of images? Well there are many to do it, but this is how I would do it,

echo "<img src=\"http://argumentum.colhome.net/dimages/".$thumb."\" width=\"150px\"/>\n";
$number = 1; // we already have 1 image ($thumb)
foreach ($images as $image) {
    echo "<img src=\"http://argumentum.colhome.net/dimages/".$image."\" width=\"150px\"/>\n";
    $number++;
    if ($number > 2) { // we get 3 images followed by a break.
	echo "</br>"; $number = 0;
    }
}

It is even better not to write ($number > 2) but to use ($number > $numcolumns) and somewhere near the top of this php file write $numcolumns = 2; That way it makes it easy to change it if you ever want to have more or less columns.
Changed the code on my page as well, http://argumentum.colhome.net/dimages/. So you can see it in action (again).

There is an even shorter way to write this:

echo "<img src=\"http://argumentum.colhome.net/dimages/".$thumb."\" width=\"150px\"/>\n";
$number = 1; // we already have 1 image ($thumb)
foreach ($images as $image) {
    echo "<img src=\"http://argumentum.colhome.net/dimages/".$image."\" width=\"150px\"/>\n";
    if ($number == 2) echo "</br>";
    $number = $number++ < 2 ? $number++ : 0;
}

A break <br> after a certain number of images? Well there are many to do it, but this is how I would do it,

echo "<img src=\"http://argumentum.colhome.net/dimages/".$thumb."\" width=\"150px\"/>\n";
$number = 1; // we already have 1 image ($thumb)
foreach ($images as $image) {
    echo "<img src=\"http://argumentum.colhome.net/dimages/".$image."\" width=\"150px\"/>\n";
    $number++;
    if ($number > 2) { // we get 3 images followed by a break.
	echo "</br>"; $number = 0;
    }
}

It is even better not to write ($number > 2) but to use ($number > $numcolumns) and somewhere near the top of this php file write $numcolumns = 2; That way it makes it easy to change it if you ever want to have more or less columns.
Changed the code on my page as well, http://argumentum.colhome.net/dimages/. So you can see it in action (again).

Ooh, I see. :) The solution wasn't too hard, as I expected. I feel like I've learned a bit about PHP on the way too. Thank you a lot, again!

if ($number > 2) { // we get 3 images followed by a break.	echo "</br>"; $number = 0;

may cause validation issues

if ($number > 2) { // we get 3 images followed by a break.	echo "<br />"; $number = 0;

may not

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.