Reputation: 319
I have create a generate random in php and insert into mysql already. But I want to loop it 1000 times when I refresh for one time. All item must go to store in database. How can I do this?
function generateCode($length = 11) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
echo $lucky_code=generateCode()."<br/>";
$servername = "localhost";
$username = "root";
$password = "";
$database = "random";
$cnt = mysql_pconnect($servername, $username, $password) or die(mysql_error());
mysql_select_db($database);
mysql_query("INSERT INTO tbl_code(code) VALUES('$lucky_code')",$cnt) or die(mysql_error());
Upvotes: 2
Views: 231
Reputation: 1864
You can use set_time_limit
before the code and run loop 1000 times as below
set_time_limit(0);
function generateCode($length = 11) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
$servername = "localhost";
$username = "root";
$password = "";
$database = "random";
$cnt = mysql_pconnect($servername, $username, $password) or die(mysql_error());
mysql_select_db($database);
for ($i = 0; $i < 1000; $i++) {
$lucky_code = generateCode();
mysql_query("INSERT INTO tbl_code(code) VALUES('".$lucky_code."')", $cnt) or die(mysql_error());
}
Upvotes: 2
Reputation: 2949
for($i = 0; $i < 1000; $i++)
{
$lucky_code = generateCode();
mysql_query("INSERT INTO tbl_code(code) VALUES('$lucky_code')",$cnt) or die(mysql_error());
}
If your maximum query size is big enough you can also try to add all rows in one query so that there is only one query (instead of 1000 queries):
$lucks_codes = array();
for($i = 0; $i < 1000; $i++) {
$lucky_codes[] = generateCode();
}
mysql_query("INSERT INTO tbl_code(code) VALUES ('".implode("'), ('", $lucky_codes)."')", $cnt) or die(mysql_error());
Please also keep in mind that the mysql extension is deprecated. Please use mysqli or PDO instead.
Upvotes: 3