Database Reference
In-Depth Information
$sth = $dbh -> exec ( "
CREATE TABLE deck
(
face ENUM('A', 'K', 'Q', 'J', '10', '9', '8',
'7', '6', '5', '4', '3', '2') NOT NULL,
suit ENUM('hearts', 'diamonds', 'clubs', 'spades') NOT NULL
)
" );
$face_array = array ( "A" , "K" , "Q" , "J" , "10" , "9" , "8" ,
"7" , "6" , "5" , "4" , "3" , "2" );
$suit_array = array ( "hearts" , "diamonds" , "clubs" , "spades" );
# insert a "card" into the deck for each combination of suit and face
$sth = $dbh -> prepare ( "INSERT INTO deck (face,suit) VALUES(?,?)" );
foreach ( $face_array as $face )
foreach ( $suit_array as $suit )
$sth -> execute ( array ( $face , $suit ));
Shuffling the cards is a matter of issuing this statement:
SELECT face , suit FROM deck ORDER BY RAND ();
To do that and store the results in an array within a script, write a shuffle_deck()
function that issues the query and returns the resulting values in an array (again shown
in PHP):
function shuffle_deck ( $dbh )
{
$sth = $dbh -> query ( "SELECT face, suit FROM deck ORDER BY RAND()" );
$sth -> setFetchMode ( PDO :: FETCH_OBJ );
return ( $sth -> fetchAll ());
}
Deal the cards by keeping a counter that ranges from 0 to 51 to indicate which card to
select. When the counter reaches 52, the deck is exhausted and should be shuffled again.
15.8. Selecting Random Items from a Set of Rows
Problem
You want to pick an item or items randomly from a set of values.
Solution
Randomize the values, then pick the first one (or the first few, if you need more than
one).
Search WWH ::




Custom Search