PDA

View Full Version : Finding First Record and Displaying


sftl99
04-30-2007, 09:43 PM
The code below is a simplified version of code that is first creating a looping gallery of thumbnails based on the URL which would have ?c=Something. Then once the link is clicked, it adds &v=SKU. Based on the SKU, I am able to display the details of the selection. It all works just fine, however in the live version I have to work in some code to account for the page not having anything to display until a thumbnail is clicked.

What I want instead, is to pull the first record available in "Collection" and display the details for that selection. I know it has to be possible...can anyone let me know how?

<? $c = $_GET['c'];
$query = "SELECT * FROM $database WHERE `Collection` = '$c' ORDER BY `SKU`";
$result = mysql_query($query) or exit(mysql_error());

if( $result ) {
while( $row = mysql_fetch_assoc($result) )
{
?><p><a href="collection.php?c=<?=$c?>&v=<?=$row['SKU']?>"><img src="images/jewelry/thumbs/<?=$row['image']?>" border="0"></a></p><?
}
} else { die( "Trouble getting contacts from database: " . mysql_error() ); }

$v = $_GET['v'];
$query = "SELECT * FROM `$database` WHERE `SKU`='$v'";
$result = mysql_query( $query );

if( $result && $database = mysql_fetch_object( $result ) )
{
$Collection = $database -> Collection;
$Type = $database -> Type;
$SKU = $database -> SKU;
$Price = $database -> Price;
$Description = $database -> Description;
$image = $database -> image;
} ?>
<?=$Collection?><br>
<?=$Type?><br>
<?=$SKU?><br>
<?=$Price?><br>
<img src="images/jewelry/<?=$image?>"><br>
<?=$Description?>

Fumigator
05-01-2007, 05:04 AM
Your script has two queries that is selecting out of the same table twice. What if you were to combine those two queries and build the "WHERE" part of your query based on the value of $_GET['v']. If it is set, then include "WHERE SKU = $_GET['v']. If it is not set, then don't include a WHERE clause at all, and use the first row in your result set to display details for that selection.

sftl99
05-01-2007, 06:58 PM
The first query must have a WHERE clause in order to know which results (thumbnails in this case) to loop through in the while statement. Make sense?

guelphdad
05-01-2007, 07:01 PM
Set your WHERE clause to

WHERE 1 = 1
which will always be true.

If you then find out that the one variable is set and you have to do a where clause to draw orders from your database then append an AND to it:


WHERE 1 = 1
AND
sku = $v


Also while you are at this thing look into the use of mysql_real_escape_string in PHP if you are not actually using it.