new to php - help with figuring out a resource

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Xorply
Forum Newbie
Posts: 1
Joined: Wed Mar 16, 2005 3:00 pm
Location: Victoria, BC

new to php - help with figuring out a resource

Post by Xorply »

Hi all and thanks in advance for your help. I'm trying to generate three different random unique results from a table and my problem comes from understanding exactly what mysql_query returns and how to access it. It returns a resource (correct?) and I want to choose three of those at random but array_rand takes it's first argument as an array and I can't wrap my head around it all. Here's my code:

Code: Select all

<?php
/* Connect to Database */
$sqlcon = mysql_connect("myServer","myUser","myPass") or die("Connection Failed: " . $mysql_error());

/* Choose the database to run queries on */
mysql_select_db("myDB") or die("Could not select database");

/* Run a query and stuff results into a variable */
$result = mysql_query("SELECT SponsorID FROM sponsors WHERE tier_level = 1");

/* Error Check */
if (!$result){
	echo 'Could not run query: ' . mysql_error();
  exit;
}

/* Select three random SponsorID's */
$randIDArray = array_rand($result, 3);

/* Choose first random SponsorID*/
$result_one = mysql_query("SELECT company_url, image_path, image_alt FROM sponsors WHERE SponsorID = $randIDArray[0]");

/* Choose second random SponsorID*/
$result_two = mysql_query("SELECT company_url, image_path, image_alt FROM sponsors WHERE SponsorID = $randIDArray[1]");

/* Choose third random SponsorID*/
$result_three = mysql_query("SELECT company_url, image_path, image_alt FROM sponsors WHERE SponsorID = $randIDArray[2]");

?>
Thanks again,

-X


feyd | Please use

Code: Select all

and

Code: Select all

tags where approriate when posting code. Read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url][/color]
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Code: Select all

SELECT * FROM table ORDER BY RAND() LIMIT 3
mysql_query() has examples of reading the results from a query.
Post Reply