我需要在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 '"';
?>发布于 2015-08-06 20:56:11
这只是一个简单的例子,太夸张了,你可能需要在随机部分中有一行。但这是我目前所拥有的全部,我必须离开。
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)
);创建一个存储过程来插入随机问题(带?at end)在调用它时一次创建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;祝好运。
发布于 2015-08-06 20:54:39
您可以创建一个包含先前插入的所有数字的数组,并将当前数字与数组中的数字进行比较:
$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 )
}https://stackoverflow.com/questions/31855422
复制相似问题