Jump to content

PHP Variables with Random SQL


JasonHarper

Recommended Posts

Hello!  I'm having a massive brain block and can't figure something out.  I have three dynamic content areas on my site (each with its own title, image, text, etc that is pulled from the DB).  I want to randomly pull three records from the DB and populate the three sets of variables accordingly but just can't seem to get it to work.  I know the code below is wrong but hopefully it will help to illustrate what I'm trying to do.  Thank you for the help!!

 

//QUERY DB FOR THREE BOX CONTENT

$result = mysql_query("SELECT * FROM content_index_boxes ORDER BY RAND() LIMIT 3");

 

while ($record = mysql_fetch_array($result, MYSQL_ASSOC))

{

$title1 = $record['title'];

$subtitle1 = $record['subtitle'];

$text1 = $record['text'];

$image1 = $record['image'];

$imagealt1 = $record['imagealt'];

$linktext1 = $record['linktext'];

$linkurl1 = $record['linkurl'];

 

$title2 = $record['title'];

$subtitle2 = $record['subtitle'];

$text2 = $record['text'];

$image2 = $record['image'];

$imagealt2 = $record['imagealt'];

$linktext2 = $record['linktext'];

$linkurl2 = $record['linkurl'];

 

$title3 = $record['title'];

$subtitle3 = $record['subtitle'];

$text3 = $record['text'];

$image3 = $record['image'];

$imagealt3 = $record['imagealt'];

$linktext3 = $record['linktext'];

$linkurl3 = $record['linkurl'];

}

 

Link to comment
https://forums.phpfreaks.com/topic/185961-php-variables-with-random-sql/
Share on other sites

Best to use an array.

 

$data = array();
while ($record = mysql_fetch_array($result, MYSQL_ASSOC)) {
    $data[] = $record;
}

 

Now you have an array containing all your data. Access the first record via $data[0]['title'], $data[0]['subtitle'] etc etc, second record via $data[1]['title'], $data[1]['subtitle'] etc etc etc.

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.