1

I can't seem to find anything on this, nor can I fix it my self after trying for hours!

The code is this:

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','')");
    }
}

The code above is suppose to generate a string randomly as many times as you want with a simple integer[POST].

When it loops it all it comes out with only 1 unique id when they're should have been (5),

and the 1 id will be the same for all the strings(31a66b9885dba85316d399d6e898b308), so it looks like this:

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

If anyone understands what i'm trying to say, please leave a comment on how to fix this, thanks!

1 Answer 1

2

You should call the function in each iteration to get another one:

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','')");
    }
}

I'd suggest use PDO with prepared statements. In this revision, you don't need to call/connect each time, take the connection also outside, and prepare the statement, which also make your queries safer to SQL injection.

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
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.