简体   繁体   中英

how to insert random value in to database mysql?

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.","; 
            }
?>

How does it differ from inserting non-random values ?

mysqli_query($link, "INSERT INTO yourtable (id, cards) VALUES (NULL, '$cards')");

Or something similar.

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

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')");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM