Создайте много строк в Mysql с помощью генератора случайных чисел php

Мне нужно создать более 1000 строк в моей базе данных MySQL. Я написал некоторый код, который генерирует случайное число с 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 '"';
?>

2

Решение

Это просто быстрый пример, излишний перебор, вам, вероятно, понадобится 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;

Удачи.

1

Другие решения

Вы можете создать массив, содержащий все числа, которые вы ранее вставили, и сравнить ваш текущий номер с тем, что в массиве:

$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 )
}
0