Page 1 of 1
Random images from the database
Posted: Thu Apr 14, 2011 7:39 am
by mickster69
Hello everyone.
This is my first time using this forum so I'm not sure if I'm writing in the right place or not.
I am creating a card game that displays 8 images per player. I need to call 8 random images (card numbers) between 1-53 from my database and then write them cards to the cardowner table connecting to the cardID, playerID and gameID.
Would really appreciate it if someone could help me with this.
Thanks
Re: Random images from the database
Posted: Thu Apr 14, 2011 9:05 am
by divedj
You have a view options to get your 8 random images from the db.
1. using the php function rand(min, max) to get a random number in a defind range and running it through a loop would give you your 8 numbers. With a select statment you get your 8 images from the db if you use continued numbering for the image_id in your db.
2. packing your 53 image names in a array and use the php function array_rand() to get your 8 random images and again use a select statment to get the data you need from your table.
There are some good examples in the php manual.
Re: Random images from the database
Posted: Thu Apr 14, 2011 11:32 am
by mickster69
Thanks for your replay divedj
I'm trying to do that first option which you have mentioned. This is the code I have at the minute for it
rand(1, 53);
$dbQuery="select id from cards values($filename, $group)";
$dbResult=mysql_query($dbQuery);
for ($i =0; $i <= 8; $i++) {
$dbQuery="insert cardID into cardowner values($playerID, $gameID)";
$dbResult=mysql_query($dbQuery);
}
Would it be something similar to this?
Re: Random images from the database
Posted: Thu Apr 14, 2011 2:19 pm
by divedj
Yep, that would have been the basic idea.
However, we need to look a bit into your syntax.
Code: Select all
//lets get our 8 numbers first
$cards = array();
for($i = 0;$i < 8;$i++)
{
$n = rand(1,53);
if(in_array($n,$cards)
{
$n = rand(1,53);
}
$cards[] = $n;
}
//here come the db queries
//asuming you have done your db connections already
//and your dataset containing playerId and gameId already exists
foreach($cards as $id)
{
mysql_query("UPDATE cardowner
SET
cardId = '".$id."'
WHERE
playerid = '".$playerId."'
AND
gameid = '".$gameId."'");
{