使用php刷新随机1000次

时间:2015-08-26 05:01:54

标签: php mysql

我已经在php中创建了一个随机生成并插入到mysql中。但是当我刷新一次时,我想循环1000次。所有项目必须存储在数据库中。我怎么能这样做?

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());

2 个答案:

答案 0 :(得分:3)

for($i = 0; $i < 1000; $i++)
{
    $lucky_code = generateCode();

    mysql_query("INSERT INTO tbl_code(code) VALUES('$lucky_code')",$cnt) or die(mysql_error());
}

如果你的maximum query size足够大,你也可以尝试在一个查询中添加所有行,这样只有一个查询(而不是1000个查询):

$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());

另请注意,我们已弃用mysql扩展程序。请改用mysqliPDO

答案 1 :(得分:2)

您可以在代码前使用set_time_limit并运行循环1000次,如下所示

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());
}