Reputation: 35
how to insert random value in to database mysql ?
Ok, when i load this code i will have random number format like this
5,3,1,6,4,
and i want to insert 5,3,1,6,4, into database mysql ( 1 row 1 column) , how can i do ?
<?
$cards = array();
for ($i = 0; $i < 5; $i++)
{
$card = mt_rand(1, 6);
if(!in_array($card, $cards))
{
$cards[$i] = $card;
}
else
{
$i--;
}
}
foreach ($cards as $cards)
{
echo $cards.",";
}
?>
Upvotes: 0
Views: 1599
Reputation: 6202
The easiest way to do what you describe would be as @Martin answered.
However this will probably screw you up later. Ideally you don't want to store a list in a RDBMS field; it defeats the whole purpose of having a database.
If you make a table like
ID, cardPosition, cardID
You can do this:
$insert = $db->prepare("INSERT INTO cardpositions (cardPosition, cardID) VALUES (:cardPosition, :cardID)");
foreach ($cards as $cardPosition=>$card)
{
$insert->execute(array(':cardPosition' => $cardPosition, ':cardID' => $card));
}
OR
The wrong way to do this, but the one you seem to want is:
$cardlist = implode(",",$cards); //now you have a comma separated list without the trailing comma
then you do this if PDO:
$insert = $db->prepare("INSERT INTO cardpositions (cardlist) VALUES (:cardlist)");
$insert->execute(array(':cardlist' => $cardlist));
or this if mysqli:
mysqli_query($link, "INSERT INTO yourtable (cardlist) VALUES ('$cardlist')");
Upvotes: 0
Reputation: 36107
Pure (My)SQL solution:
INSERT INTO test( x, y )
SELECT 10*rand(),
10*rand()
FROM information_schema.columns
LIMIT 10;
Demo: http://www.sqlfiddle.com/#!2/be6e5/2
Upvotes: 0
Reputation: 2028
How does it differ from inserting non-random values ?
mysqli_query($link, "INSERT INTO yourtable (id, cards) VALUES (NULL, '$cards')");
Or something similar.
Upvotes: 1