简体   繁体   中英

MySQL and Do While loop timing out

This is timing out without echo-ing anything as well as not inserting into database. Can't see why. Any ideas?

Note It's to simply generate a number of code numbers, I'm aware that it's simple and insecure, it's being done on localhost only and the connection values are sound.

function populate_codes(){
  $con = mysql_connect(dbhost,dbuser,dbpass);
  mysql_select_db(dbname);
  $i = 0;
  do{
    $code = rand(10000000,99999999);
    $check = mysql_query('SELECT * FROM '.dbcodetable.' WHERE code = $code',$con);
    if(!$check){
        $insertcode = mysql_query('INSERT INTO '.dbcodetable.' (code,status) VALUES ($code,1)',$con);
        if($insertcode){
            echo $i.' - '.$code.'<br />';
            $i++;
        }
     }
  }
  while($i <= 1999);
  echo "------------------------<br /><strong>Complete</strong>";
}

You:

  1. set $i to 0
  2. generate a random number
  3. perform an SQL query
  4. check if the query execution returned false
  5. only if it did, and some more conditions apply, are you finally incrementing $i
  6. you repeat this until $i is incremented beyond 1999

The problem is that your 4th step always succeeds . The query always executes successfully, mysql_query always returns a result set . You have to inspect the result set to see what's in it, not just test it against == false . So, $i never increments.

You also want to increment $i outside all those ifs, or have a general protection against infinite loops.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM