There is a script that fills the database with data taken from the array. Now the data from the array is added randomly, how can the script be changed so that the data is added sequentially (One, Two, Three, .., .., One, Two, .......)?

Php:

if(100==100){ $rowsToCreate = 30; $name = array("Один", "Два", "Три", "Четыре", "Пять"); $text = array("Текст 1", "Текст 2", "Текст 3", "Текст 4", "Текст 5"); do { $name2 = $name[array_rand($name)]; $text2 = $text[array_rand($text)]; $data = "INSERT INTO `blog` (id, name, text) VALUES (NULL, '".$name2."', ' ".$text2."' ) "; $Result = mysql_query($data); $rowsToCreate--; } while ($rowsToCreate>=1); if ($Result) { echo "<h3>Информация добавлена!!</h3>"; }else{ echo "<h3>Увы, но информация не добавлена!!</h3>"; } } 

Bd:

 CREATE TABLE IF NOT EXISTS `blog` ( `id` int(10) NOT NULL AUTO_INCREMENT, `name` varchar(100) NOT NULL, `text` varchar(100) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ; 
  • you make a simple for ($i = 0; $i < $rowsToCreate ; $i++) {...} loop for ($i = 0; $i < $rowsToCreate ; $i++) {...} , and in the loop you get the current index through $currentIndex = $i % count($name); - BOPOH
  • And why are you doing INSERT INTO (id.. ) VALUES (NULL ? Don't you have an id PRIMARY KEY? - cyadvert
  • @cyadvert And what is the best way to do ( INSERT INTO (id.. ) VALUES (NULL )? - user185447
  • If the id is PRIMARY KEY and AUTO INCREMENT, then it is not needed at all. The base itself will create: INSERT INTO blog (name, text) VALUES ('".$name2."', ' ".$text2."' ) - cyadvert

1 answer 1

That's the way to go?

 $inArrayCnt = 0; // здесь будем хранить порядковый номер записи из массива do { $name2 = $name[$inArrayCnt]; $text2 = $text[$inArrayCnt]; $data = "INSERT INTO `blog` (id, name, text) VALUES (NULL, '".$name2."', ' ".$text2."' ) "; $Result = mysql_query($data); $rowsToCreate--; $inArrayCnt++; // увеличиваем порядковы номер if ($inArrayCnt==Count($name)) $inArrayCnt=0; // если новый номер последний - обнуляем счетчик } while ($rowsToCreate>=1); 
  • Great, thanks from me +. - user185447