gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 02:54:45 26 4
gpt4 key购买 nike

我需要在我的 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 '"';
?>

最佳答案

这只是一个简单的示例,太过分了,您可能需要在随机部分中添加 1 行。但这就是我目前所拥有的一切,必须离开。

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;

祝你好运。

关于php - 使用 php 随机数生成器在 Mysql 中创建多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31855422/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com