Jump to content

[SOLVED] Random Row Display


jj20051

Recommended Posts

I Made The Code Bellow To Display Every A Row In A Database. Now I Would Like To Make It So That It Displays Only One Random Row... Here Is My Code:

 

$sqlstr = mysql_query("SELECT * FROM products");
if (mysql_numrows($sqlstr) != 0) {
while ($row = mysql_fetch_array($sqlstr)) {
?>
<p><?= $row['name'] ?></p>
<p><?= $row['description'] ?></p>
<p><img src="<?= $row['image'] ?>"></p>
<?php
}
}

 

P.S. - Help With Code Would Be Great Since I'm Not that Great At Visualizing PHP Code In My Head Yet.. but Whatever Help You Do Give Thanks In Advance!

Link to comment
https://forums.phpfreaks.com/topic/126987-solved-random-row-display/
Share on other sites

This should do the trick:

$query = "SELECT * FROM products ORDER BY rand() LIMIT 1"
$result = mysql_query($query);

$row = mysql_fetch_row($result);

echo '<p>'.$row['name'].'</p>';
echo '<p>'.$row['description'].'</p>';
echo '<p><img src="'.$row['image'].'"></p>';

Oops! Thanks for pointing that out.

 

$query = "SELECT * FROM products ORDER BY rand() LIMIT 1"
$result = mysql_query($query);

$row = mysql_fetch_assoc($result);

echo '<p>'.$row['name'].'</p>';
echo '<p>'.$row['description'].'</p>';
echo '<p><img src="'.$row['image'].'"></p>';

I'm not sure why I did that, but its fixed now :)

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.