使用php随机数生成器在Mysql中创建许多行


Create many rows in Mysql with php random number generator

我需要在我的mysql数据库中创建超过1000行。我写了一些代码,生成一个随机数,有5个整数,数字在2-8之间。

我想用生成的数字在数据库中创建一个新行。

我有这一切,但我不知道让代码记住已经插入的值。

是否有一种方法可以做到这一点,而不必在数组中存储所有值,然后在插入新行之前使代码检查孔数组?

有更聪明的方法吗?

我代码:

$length = 5;
echo '"';
for ($i = 0; $i < $length; $i++) {
    echo generateRandomString('3'). '", "';
}

function generateRandomString($length = 10) {
    $characters = '2345678';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}
echo '"';
?>

这只是一个简单的例子,有点小题大做,你可能需要在随机部分加一行。但这是我目前仅有的一切,我得走了。

create schema so_gibberish; -- creates database 
use so_gibberish;   -- use it 
-- drop table random;   -- during debug
create table random 
(   id int auto_increment primary key,
    question varchar(50) not null,
    category int not null,
    randomOrder int not null,
    key (category)
);

创建一个存储过程来插入随机问题(带有?在结束)当你调用

时,一次创建300
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
DELIMITER $$ 
drop procedure if exists createRandomQuestions$$ 
-- 17 categories of questions randomly created. yes random word questions and categories.
create procedure createRandomQuestions()
BEGIN
set @i=1;
WHILE @i<=300 DO
insert random (question,category) values ('xxx',1);
SELECT @lid:=LAST_INSERT_ID();  -- use id to seed, next 8 guaranteed different i think
-- programmer should come up with adequate random seed on their own
-- this is WAY overkill but it was what I had at the moment to show you
UPDATE random SET question=concat(
substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', rand(@seed:=round(rand(@lid)*4294967296))*36+1, 1),
substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', rand(@seed:=round(rand(@seed)*4294967296))*36+1, 1),
substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', rand(@seed:=round(rand(@seed)*4294967296))*36+1, 1),
substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', rand(@seed:=round(rand(@seed)*4294967296))*36+1, 1),
substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', rand(@seed:=round(rand(@seed)*4294967296))*36+1, 1),
substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', rand(@seed:=round(rand(@seed)*4294967296))*36+1, 1),
substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', rand(@seed:=round(rand(@seed)*4294967296))*36+1, 1),
substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', rand(@seed)*36+1, 1), ' ?'
), category=floor(rand()*17+1),randomOrder=0
WHERE id=@lid;
set @i=@i+1;
END WHILE;
END;
$$
DELIMITER ;
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

称之为:

call createRandomQuestions();
清理:

drop schema so_gibberish;

好运。

你可以创建一个数组来保存你之前插入的所有数字,并将你当前的数字与数组中的数字进行比较:

$inserted_numbers = array()
if( in_array( $number, $inserted_numbers ) ) {
     // The numbers is already in the array 
} else {
     // NUmber not in array, do stuff
     array_push( $inserted_numbers, $number )
}