Php and sql question

Associate
Joined
13 Nov 2003
Posts
1,567
Location
Manchester
Hi All

Quick question here. I need to output the last 4 records from a db. However due to the way the page has been designed I cant use repeat regions to display them.

Is there a way to output each record as a set of strings. So I could have $id1, $id2 etc which I can then print out later in the page

Cheers
Aaron
 
you could grab them from the db into an array?

Code:
$query = "SELECT * FROM table ORDER BY date DESC LIMIT 4";
$result = mysql_query($query);
$num = mysql_num_rows($result);

for ($i = 0; $i < $num; $i++){

$array[$i] = mysql_fetch_array($result);

}

that assumes that you're using Mysql as opposed to SQL though...i'm sure it's not a lot different for SQL :)
 
I was thinking it would be something like that.

Dont mean to annoy you lol, but assuming there are 4 records and I need to get the name, and flyerid fields from each how would I set out the array bit, ive never used arrays before
Ta
Aaron
 
that'll allow you to refer to specific fields from the array...refer to them thus:

Code:
print_r ($array[0][flyerid])
print_r ($array[1][flyerid])
print_r ($array[2][flyerid])
print_r ($array[3][flyerid])

and the same for name, but replace "flyerid" with "name". if you're doing them next to each other, it might be worth using a foreach loop...what are you using the values for?
 
Thanks for that, makes more sense now

The values will be used to select the url of the flyer image in a query which will then be echoed out somewhere on the page to load the image

Ta

Aaron
 
Hmm its not working.

This is the first query that calls the relevant events, flyerurl is the ID of the relevant flyer image in the flyerstable

Code:
mysql_select_db($database_essential, $essential);
$eventsquery = "SELECT * FROM events ORDER BY id DESC LIMIT 4";
$result = mysql_query($eventsquery);
$num = mysql_num_rows($result);

for ($i = 0; $i < $num; $i++){

$array[$i] = mysql_fetch_array($result);

}

And this is the code that uses the array results to fetch the relevant image url from the flyers table

Code:
<?php $flyer_query = mysql_query("SELECT * FROM flyers WHERE id='$array[0][flyerid]' LIMIT 1") or die("There was an error accessing the flyers table" . mysql_error());
while ($row = mysql_fetch_array($flyer_query)) {
   $flyer1 = $row["ImageUrl"];
} ?>

Thanks
Aaron
 
Edit... The first chunk of code is working. As I can print the results out, its the bit that gets the image url that is borkerised
 
Back
Top Bottom