简体   繁体   English

如何在数据库mysql中插入随机值?

[英]how to insert random value in to database mysql?

how to insert random value in to database mysql ? 如何在数据库mysql中插入随机值?

Ok, when i load this code i will have random number format like this 好的,当我加载此代码时,我将具有这样的随机数格式

5,3,1,6,4, 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 ? 我想将5,3,1,6,4插入数据库mysql(1行1列)中,我该怎么办?

<?
    $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: 纯(My)SQL解决方案:

INSERT INTO test( x, y )
SELECT 10*rand(),
       10*rand()
FROM information_schema.columns
LIMIT 10;

Demo: http://www.sqlfiddle.com/#!2/be6e5/2 演示: http ://www.sqlfiddle.com/#!2/ be6e5/2

The easiest way to do what you describe would be as @Martin answered. 做您描述的最简单的方法是@Martin回答。

However this will probably screw you up later. 但是,这可能会在以后给您带来麻烦。 Ideally you don't want to store a list in a RDBMS field; 理想情况下,您不想在RDBMS字段中存储列表。 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: 然后,如果PDO执行此操作:

$insert = $db->prepare("INSERT INTO cardpositions (cardlist) VALUES (:cardlist)");
$insert->execute(array(':cardlist' => $cardlist));

or this if mysqli: 如果mysqli,则为:

mysqli_query($link, "INSERT INTO yourtable (cardlist) VALUES ('$cardlist')");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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