0

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

3 Answers 3

1

How does it differ from inserting non-random values ?

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

Or something similar.

Sign up to request clarification or add additional context in comments.

1 Comment

not work , when i use your code , it's will be insert only first number into mysql (not all of data )
0

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

Comments

0

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

4 Comments

i want to make a table like ID, number in number column i want to insert 5,3,1,6,4, how can i do ?
It means I don't know what you are talking about: put the table definition in the question.
OK, i will make table that have 2 column 1.id and 2. number, and i want to insert 5,3,1,6,4, to column number
what you call "number" i call "cardlist" in the answer above. Take a look... cardlist is a better name than number because it describes what is actually in the field.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.