Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Display specific images with mysql / PHP 2

Status
Not open for further replies.

Programz8

Programmer
Mar 27, 2007
33
US
Greetings all:

I'm trying to figure out how I can pull an image from my database and display it on my website. I ONLY WANT A SPECIFIC image that I can call by the id number. I have bigimage and image as fields on a table in my DB. How can I call only specific images instead of using an array or random image display?


I want to display the image(s) on a page called kma_steelo.php

So can I somehow write a line of code like this
echo kma_steelo.php?$bigimage?id=5
echo kma_steelo.php?$image?id=22

Or would it be a line of code like
echo $bigimage.php?id=5
echo $image.php?id=23

??????????????????????????????????????????????????


Thanks.






 
O.k I think I understand.

You want to create the link list by pulling it out form the Db so you can edit the DB and it automatically reflects in the page correct?









----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.
 
Okay to clear things up here is a sample of code that accomplishes what I want to do the only thing is that I want to be able to show another image right next to this one but only a different image and text. So I can have multiple sets of images and text on one page. For now I'll have to go in and manually update the new id numbers and text until I can find a simpler way to change that but the most important issue is being able to show more than one image on a page.

<?
// Start a session or continue one.
session_start();
// Start an if block that checks the value of $valid
if ($_SESSION[valid] != "yes") {
session_register('valid'); }

$db_name = "cayema"; $table_name = "Art";
$connection = @mysql_connect("localhost", "cayema", "**") or die (mysql_error());
$db = @mysql_select_db($db_name,$connection) or die(mysql_error());
$sql ="SELECT article_name, image, text, bigimage, alttext FROM $table_name WHERE a_id = \"12\" ";
$result = @mysql_query($sql,$connection) or die ("aint gonna be able to do it");

// Start while loop to create array for $row variable for each record in result set
while ($row = mysql_fetch_array($result)) {

// Get individual elements of the record and give them good names.
$article_name = $row[article_name];
$image = $row[image];
$text = $row[text];
$bigimage = $row[bigimage];
$alttext = $row[alttext];

}

?>

<html>
<a href="kma_ce.php?a_id=12"><? echo "$image"; ?><? echo "$text"; ?></a>
</html>
 
here is the code i posted above commented as requested.

save it to a new page and just point your browser at it to see what it does (which i hope is what you want)

Code:
<?
//attach to the database here
$db_name = "database"; 
$tablename = "example";
$connection = @mysql_connect("localhost", "database", "***") or die (mysql_error());
$db = @mysql_select_db($db_name,$connection) or die(mysql_error());

/* this code is split into three distinct 'bits' - each is organised as a function
displayImages does the work of outputting the images
parseintoarray takes the input from the user form and makes an array for displayimages to use
displayForm takes all the image NAMES from the database and creates a list of them with a checkbox so that you can select the images that you want to display.

*/
if (isset($_POST['submit'])){	//check whether the user has submitted the form
	displayImages();	//if yes, start displaying the images
} else {
	displayForm();		//if not, then display the list of images for the user to make a choice
}
function displayImages(){
	global $tablename;	//the variable is defined outside a function. to make it available to a function we use the global keyword
	$ids = parseIntoArray(); //this causes the parseintorarray function to fire up.  the output of the function is assigned to $ids
	$sql = "SELECT article_name, image, text, bigimage, alttext,id FROM $tablename WHERE id IN (". implode(",", $ids) . ")";  // the mysql IN keyword is used here.  the implode function takes the array and makes it into a nice comma delimited string for the IN function to use
	$result = mysql_query($sql) or die (mysql_error());	//perform the query
	while ($row = mysql_fetch_assoc($result)){	//iterate through the recordset 
	  $image = str_replace ("src=", "alt=\"".$row['alttext']."\" src=", $row['image']); //this line takes the normal image tag that is stored in the db and inserts the alttext into it
	  echo <<<HTML
	 <a href="kma_ce.php?id={$row['id']}">{$image}{$text}</a><br/>
HTML;
	//output the links and the images at the moment they are just in a vertical column
	}
}

function parseIntoArray(){
	//get a list of actual ids to cross check user input
	global $tablename;
	$validID = array();	//instantiate the array - just good practice
	/*
		what we are doing here is getting an array of all the id's in the database.  
		these are the KNOWN GOOD VALUES
		the user input  should ALWAYS be considerer tainted.  so ideally you will test 
		each user value against the Known good values and discard those that do not match.
		
		we do this here by selecting all the id's and then iteratively putting them into an array.
		the incoming checkboxes are available to php in the $_POST['id'] variable which is itself an array.
		the array is organised so that its keys are the ids.  this is caused by the way we put the form together in display form.
		
		to check the values we iterate over the array and check with each value (in fact the key) is in the array of known good values.  if it is then we add the id onto the valid_id array
	*/
	$sql = "select id from $tablename";	
	$result = mysql_query($sql) or die (mysql_error());
	while ($row = mysql_fetch_assoc($result)){
		$permittedID[] = $row[0];	//create the array of known good values
	}
	
	foreach($_POST['id'] as $id=>$val){		//iterate through the incoming array of ids
		if (in_array($id, $permittedID)){	//check to make sure an incoming value is valid
			$validID[] = $id;				// if it is valid, assign to a validated array
		}
	}
	return $validID;						// return the clean array to the calling functino
}
function displayForm(){
	/*
	this function is very simple.  it just grabs all the ids and the names from the database and outputs
	a form to the screen that allows the user to select those images that he wants displayed
	*/
	global $tablename;
	$sql = "select `text`, id from $tablename";
	$result = mysql_query($sql) or die (mysql_error());
	//the syntax below is called the HEREDOC syntax.  it is used most often for outputting chunks of html
	$output = <<<STYLE
<style type="text/css">
.even_row {width:60%; margin:0 auto; border: 1px black solid; background-color:#FFFFFF;}
.odd_row {width:60%; margin:0 auto; border: 1px black solid; background-color:#CCCCFF;}
.cbox {width: 20px;}
</style>
<form action="{$_SERVER['PHP_SELF']}" method="post">

STYLE;
	while ($row = mysql_fetch_assoc($result)){
		$class = ($class=="even_row") ? "odd_row" : "even_row";	//this is just a stylistic tweak
		$output .= <<<HTML
	<div class="{$class}">
		<label for="id[{$row['id']}]">
			<span class="cbox">
				<!--THIS IS THE IMPORTANT BIT. NAME THE CHECKBOX AS AN ARRAY SO THAT IT IS USABLE IN PHP-->
				<input type="checkbox" name="id[{$row['id']}]" id="id[{$row['id']}]" />
			</span>
			<span class="label">
				{$row['text']}
			</span>
		</label>
	</div>
HTML;
	}
	$output .= <<<HTML
	<div class="row">
		<input type="submit" name="submit" value="Get Photos" />
	</div>
	</form>
HTML;
	
	echo $output;	//SEND THE FORM TO THE SCREEN
}
?>
 
Yes I need to do 2 things as demonstrated by the code in my last post.

1) Be able to add multiple different images to a page instead of one. The problem is that if I do a select statement that pulls several records how can I display each record on the page where I want them? There has to be some kind of code that will indicate where each image will go.
2) If possible find a simpler way to change the image when a new product is added.

I really do appreciate the help, thanks.

Programz
 
In reading through this post and looking at your 'static' html demonstration page it might wise to use a more complex query and some structures. It sounds and looks to me like you're going to want to ad a product category field along side the image link in the database so you can pull all the 'womens shirts' and display them dynamically on a specific page. Am i right in my assessment of the situation?

If I were attacking this problem I would alter the database structure so that I had an int field called prod_type_id. this table would correspond to a second table with the types and definitions.

Since it sounds like your inventory is going to be changing hard coding based on id's isn't going to be beneficial as the products change. So my select might look something like this:

Code:
//function to get all womens dkny tops
function getprodimg($type) {
$dbmgr = new DBManager();
$qry = "select * from table where prod_type_id = $type";
$dbmgr->execQuery($qry);

$num_rows = $dbmgr->numrows();
$getworktypeArray = array();	

if(!$num_rows) {
	return $getimgtypeArray; //if num_rows is empty return empty array;
	}
//for each row add an iteration to the array
for($i = 0; $i < $num_rows; $i++) {
	$result = $dbmgr->next($i);
	$gettype = new prodtype();
	$gettype->img_id = $result['IMG_ID'];
		
 $getimgtypeArray[$i] = $gettype;
	}
     //return the array to the called function
	return $getimgtypeArray;
}
}



//build the basic structure of the page with your headers etc
echo "<table border=0 cols=3><tr><td>Place 1</td><td>Place 2</td><td>Place 3</td></tr>";

//begin your first row
echo "<tr>";
//place this section where you want to use the images
//call to function giving the product type you want

$imgid = getprodimg($type=5);

foreach($imgid as $imgid) {
$id = $imgid->img_id;
echo "<td><img src='$id.jpg'><br><a href='newdoc.html?id=$id'>Description</a></td>";
}

//close your table and your done

echo "</table>";

I use some dynamic table programs to draw my tables, but I hope that gives you an idea of what you can do. I've demonstrated this at she has multiple books that we store the information in a database, each book has an image link similar to what you're talking about.

hope this is helpful


"If the only prayer you said in
your whole life was, 'thank you,'
that would suffice."
-- Meister Eckhart
 
After reading your posts, i got the feeling all you wanted to do was:
$db_name = "cayema"; $table_name = "Art";
$connection = @mysql_connect("localhost", "cayema", "**") or die (mysql_error());
$db = @mysql_select_db($db_name,$connection) or die(mysql_error());
$sql ="SELECT article_name, image, text, bigimage, alttext, id FROM $table_name;

[green]notice I removed the Where part of your query, and added id to retrieve the ID also. [/green]

$result = @mysql_query($sql,$connection) or die ("aint gonna be able to do it");

while($row=mysql_fetch_array($result)){

$article_name = $row[article_name];
$image = $row[image];
$text = $row[text];
$bigimage = $row[bigimage];
$alttext = $row[alttext];
$id=$row['id']
echo "<a href='kma_ce.php?a_id=$id'>$image $text</a>";

}

This will actually go through the results and output a link and an image for each row gotten from the DB.


----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.
 
Thank you all for the help and suggestions, Vacunita yes you have it right that is what I wanted to do but I wanted to be able to choose which images to be output rather than just showing every image. With the help aquired from Vacunita, Jpadie and Bijae I should be able to combine some of your ideas and come up with some code to achieve what I want. I thank you all and I'll keep you updated and show you the new code when I'm finished with it.


Programz.
 
From my example just add the Id's you want to the Where clause. how you get those Id's i don;t know. But its just a matter of using the array we discussed earlier, in conjunction with my last example. That should get you where you need to go.

And I'm glad we were able to help you out after all that.:p

----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.
 
JPadie I'm trying to implement your code and I have an error I can't find. It is an SQL error somewhere next to the ")" in line 1 ???????? Do you see the error?

//attach to the database here
$db_name = "slow";
$tablename = "Art";
$connection = @mysql_connect("localhost", "slow", "**") or die (mysql_error());
$db = @mysql_select_db($db_name,$connection) or die(mysql_error());

/* this code is split into three distinct 'bits' - each is organised as a function
displayImages does the work of outputting the images
parseintoarray takes the input from the user form and makes an array for displayimages to use
displayForm takes all the image NAMES from the database and creates a list of them with a checkbox so that you can select the images that you want to display.

*/ /// Line 20
if (isset($_POST['submit'])){ //check whether the user has submitted the form
displayImages(); //if yes, start displaying the images
} else {
displayForm(); //if not, then display the list of images for the user to make a choice
}
function displayImages(){
global $tablename; //the variable is defined outside a function. to make it available to a function we use the global keyword
$ids = parseIntoArray(); //this causes the parseintorarray function to fire up. the output of the function is assigned to $ids
$sql = "SELECT article_name, image, text, bigimage, alttext, a_id FROM $tablename WHERE a_id IN (". implode(",", $ids) . ")"; // the mysql IN keyword is used here. the implode function takes the array and makes it into a nice comma delimited string for the IN function to use
$result = mysql_query($sql) or die (mysql_error()); //perform the query
while ($row = mysql_fetch_assoc($result)){ //iterate through the recordset
$image = str_replace ("src=", "alt=\"".$row['alttext']."\" src=", $row['image']); //this line takes the normal image tag that is stored in the db and inserts the alttext into it
echo <<<HTML
<a href="kma_ce.php?a_id={$row['a_id']}">{$image}{$text}</a><br/>
HTML;
//output the links and the images at the moment they are just in a vertical column
}
}
//line 39
function parseIntoArray(){
//get a list of actual ids to cross check user input
global $tablename;
$validID = array(); //instantiate the array - just good practice
/*
what we are doing here is getting an array of all the id's in the database.
these are the KNOWN GOOD VALUES
the user input should ALWAYS be considerer tainted. so ideally you will test
each user value against the Known good values and discard those that do not match.

we do this here by selecting all the id's and then iteratively putting them into an array.
the incoming checkboxes are available to php in the $_POST['a_id'] variable which is itself an array.
the array is organised so that its keys are the ids. this is caused by the way we put the form together in display form.

to check the values we iterate over the array and check with each value (in fact the key) is in the array of known good values. if it is then we add the id onto the valid_id array
*/
$sql = "select a_id from $tablename";
$result = mysql_query($sql) or die (mysql_error());
while ($row = mysql_fetch_assoc($result)){
$permittedID[] = $row[0]; //create the array of known good values
}
//line 61
foreach($_POST['a_id'] as $ids=>$val){ //iterate through the incoming array of ids
if (in_array($ids, $permittedID)){ //check to make sure an incoming value is valid
$validID[] = $ids; // if it is valid, assign to a validated array
}
}
return $validID; // return the clean array to the calling functino
}
function displayForm(){
/*
this function is very simple. it just grabs all the ids and the names from the database and outputs
a form to the screen that allows the user to select those images that he wants displayed
*/
global $tablename;
$sql = "select `text`, `image`,a_id from $tablename";
$result = mysql_query($sql) or die (mysql_error());
//the syntax below is called the HEREDOC syntax. it is used most often for outputting chunks of html
$output = <<<STYLE
<style type="text/css">
.even_row {width:60%; margin:0 auto; border: 1px black solid; background-color:#FFFFFF;}
.odd_row {width:60%; margin:0 auto; border: 1px black solid; background-color:#CCCCFF;}
.cbox {width: 20px;}
</style>
<form action="{$_SERVER['PHP_SELF']}" method="post">

STYLE;
while ($row = mysql_fetch_assoc($result)){
$class = ($class=="even_row") ? "odd_row" : "even_row"; //this is just a stylistic tweak
$output .= <<<HTML
<div class="{$class}">
<label for="a_id[{$row['a_id']}]">
<span class="cbox">
<!--THIS IS THE IMPORTANT BIT. NAME THE CHECKBOX AS AN ARRAY SO THAT IT IS USABLE IN PHP-->
<input type="checkbox" name="a_id[{$row['a_id']}]" a_id="a_id[{$row['a_id']}]" />
</span>
<span class="label">
{$row['text']}
</span>
</label>
</div>
HTML;
}
$output .= <<<HTML
<div class="row">
<input type="submit" name="submit" value="Get Photos" />
</div>
</form>
HTML;

echo $output; //SEND THE FORM TO THE SCREEN
}
?>
 
nope can't see any errors.

what's the precise message that you are getting?
 
You have an error in your SQL syntax. Check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 1
 
well ... that's helpful!

can you remove the prepended @signs and rerun the code.
also change each instance of die(mysql_error()) to
Code:
die ("Mysql error: ".mysql_error()."<br/>query was: $sql <br/>Line : ". __LINE__);
 
Tell me about it i've been looking at this code since 8:00 AM, without knowing what to look for but hey atleast now I know a new method for error handling. The new error is.

Mysql error: You have an error in your SQL syntax. Check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 1
query was: SELECT article_name, image, text, bigimage, alttext, a_id FROM Articles WHERE a_id IN ()
Line : 32
 
this means that ths ids are not getting passed to the file.
can you make the following changes

Code:
    while ($row = mysql_fetch_[red]array[/red]($result)){
        $permittedID[] = $row[[red]'a_id'[/red]];    //create the array of known good values
    }

Code:
$ids = parseIntoArray();
[red]echo "DEBUG ONLY: <br/><pre>".print_r($ids, true)."</pre>"[/red]

we may also need to check inside the form handling function but let's take it one step at a time.
 
Jpadie that worked I had to add a semicolon to the debug line but that is fine. This is a system will do exactly what I want but I will need to make 3 modifications.

1) can I direct the new page that is generated to a specific page?

2) Can I add text under the images

3) How can I edit the page for spacing for the images such as show five on a row or 4 in a row then the rest on the next page.

Thanks.
 
please ignore the above. not thinking straight. all you need do is this to fix it:

Code:
while ($row = mysql_fetch_assoc($result)){
        $permittedID[] = $row['a_id'];    //create the array of known good values
    }
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top