0

My php code generates a random bank account number when registering a user. When $wszystko_ok == true, let him register.

This code checks if the generated number already exists in the database. If it exists, set $wszystko_ok = false and it doesn't agree to the account registration.

How can I make it generate a random number again in this case?

$wszystko_ok == true
$r_nrkonta = rand(1000000000, 9999999999);

$rezultat2 = $polaczenie->query("SELECT nrkonta FROM kontabankowe WHERE nrkonta='$r_nrkonta'");
if (!$rezultat2)
    throw new Exception($polaczenie->error);

$ile_takich_nrkonta = $rezultat2->num_rows;
if ($ile_takich_nrkonta > 0)
{
    $wszystko_ok = false;
}
KhorneHoly
  • 4,666
  • 6
  • 43
  • 75
FSp1333
  • 55
  • 6
  • On which condition you want to generate random code again? –  Jun 11 '18 at 08:54
  • define a function with rand(1000000000, 9999999999) and call the function when ever it is required. – Vamsi Krishna Jun 11 '18 at 08:55
  • For the record, your code is vulnerable to [SQL Injection](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php), you should use prepared statements in your SQL. Even if you're generating the value in this case, you should do it right every time at beast. – KhorneHoly Jun 11 '18 at 08:56
  • throughout the above code. – FSp1333 Jun 11 '18 at 08:56
  • Where you set ok to false, generate again there – Liam G Jun 11 '18 at 09:10

2 Answers2

1

Here the in_array call is substituted for your SQL SELECT for simplicity.

<?php

$acs = 
[
    '1',
    '2',
    '3'
];

$limit = 10;
$tries = 0;
while(true)
{
    $tries++;
    if($tries >= $limit)
        throw new Exception('New AC number generation attempts exceeded.');

    $new_ac = rand(1,10);
    if(!in_array($new_ac, $acs))
        break;
}

var_dump($new_ac, $tries);
Progrock
  • 7,373
  • 1
  • 19
  • 25
0

You need to use a do-while loop:


do {   
    $wszystko_ok = true; 
    $r_nrkonta = rand(1000000000, 9999999999);

    $rezultat2 = $polaczenie->query("SELECT nrkonta FROM kontabankowe WHERE nrkonta='$r_nrkonta'");
    if (!$rezultat2)
        throw new Exception($polaczenie->error);

    $ile_takich_nrkonta = $rezultat2->num_rows;
    if ($ile_takich_nrkonta > 0)
    {
        $wszystko_ok = false;
    }
} while ($wszystko_ok == false);

I am just guessing the meaning of your variables, but i think you get the idea.

John Lim
  • 455
  • 4
  • 4
  • I've tried this kind of solution sooner and it always sends a query to mysql. I don't know why this is no working. – FSp1333 Jun 11 '18 at 09:15