Jump to content

How would I create random display of multiple fields


simcoweb

Recommended Posts

I'm doing a sort of 'random quote' but it's going to display 5 items instead of just 1 and will be pulling from a MySQL database instead of a text file. With that said, I visited the tutorials here and found one that shows how to pull the one field ['messages'] but I need to pull these:

name
headline
message
photo
date

The snippet of code from the tutorial is:

[code]<?
$cnx = mysql_connect("localhost", "root", "");
mysql_select_db("irclog", $cnx);
$sql = mysql_query("SELECT message FROM irclog") or die (mysql_error());
while($row = mysql_fetch_array($sql)){
    $row_array[] = $row['message'];
}
mysql_close($cnx);
$random_row = $row_array[rand(0, count($row_array) - 1)];
echo $random_row;
?> [/code]

I have the mysql stuff, no problem. The fetching of the array pulls just the $row['message'] field. I'm sure that's where I need to expand and i'm assuming I would do it sort of like this:

$row_array[] = $row['name'], $row['headline'], $row['photo'], $row['message'], $row['date'];

Then the remaining code would stay the same. Would this be the proper way?
What your code does now:
Fetches the ENTIRE table from MySQL, sends it an array in PHP, then echos a random row in the array.

What these nice people are showing you how to do:
Fetch a random row from MySQL, then echo those rows with PHP.


So, using their query, you can replace all this garbage:
[code=php:0]while($row = mysql_fetch_array($sql)){
    $row_array[] = $row['message'];
}
mysql_close($cnx);
$random_row = $row_array[rand(0, count($row_array) - 1)];
echo $random_row;[/code]

With just this:
[code=php:0]($row = mysql_fetch_array($sql)){
    echo $row['message'];
    echo $row['whateverothercolumyouwant'];
}
mysql_close($cnx);[/code]

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.