循环保持相同的字符串

时间:2015-04-18 05:56:08

标签: php mysql

我似乎无法在此找到任何东西,在尝试了几个小时之后我也无法自行修复它!

代码是这样的:

function generatecode()
{
    $token = md5(uniqid(rand(), true));
    return $token;
}


$number = $_POST['number'];
$service = $_POST['service'];
$token = generatecode();
if ($service == ""){

} 
else {
    for ($x = 0; $x <= $number; $x++) {
        $con = mysql_connect($host,$username,$password);
        mysql_select_db("$db_name", $con);
        mysql_query("INSERT INTO tokens (id, token, service, used, usedby) VALUES(NULL, '$token','$service','0','')");
    }
}

上面的代码假设使用简单的整数[POST]随机生成一个字符串。

当它循环播放时,只有1个唯一ID,当它们应该是(5)时,

并且所有字符串(31a66b9885dba85316d399d6e898b308)的1 id都相同,所以它看起来像这样:

 - 31a66b9885dba85316d399d6e898b308 
 - 31a66b9885dba85316d399d6e898b308
 - 31a66b9885dba85316d399d6e898b308 
 - 31a66b9885dba85316d399d6e898b308
 - 31a66b9885dba85316d399d6e898b308

如果有人理解我想说的话,请留下评论如何解决这个问题,谢谢!

1 个答案:

答案 0 :(得分:2)

你应该在每次迭代中调用函数来获得另一个函数:

function generatecode() {
    $token = md5(uniqid(rand(), true));
    return $token;
}

$number = $_POST['number'];
$service = $_POST['service'];
if ($service == ""){

} 
else {
    for ($x = 0; $x <= $number; $x++) {
        $con = mysql_connect($host,$username,$password);
        // instead of outside, put it inside the loop
        $token = generatecode();
        mysql_select_db("$db_name", $con);
        mysql_query("INSERT INTO tokens (id, token, service, used, usedby) VALUES(NULL, '$token','$service','0','')");
    }
}

我建议将PDO用于准备好的语句。在本次修订中,您不需要每次都调用/连接,也可以在外部进行连接,并准备语句,这也使您的查询更安全。[/ p>

if (!empty($_POST['service'])){

    $number = $_POST['number'];
    $service = $_POST['service'];

    $db = new PDO("mysql:host={$host};dbname={$dbname}", $username, $password);
    $insert = $db->prepare("INSERT INTO `tokens` (id, token, service, used, usedby) VALUES(NULL, :token, :service, '0', '')");
    for ($x = 0; $x <= $number; $x++) {
        $token = generatecode();
        $insert->execute(array(
            ':token' => $token,
            ':service' => $service,
        ));
    }
} 
else {
    // do something else
}