0

I'm trying to do that in PHP.

This code should insert 500000 rows in users table and after each row should print the value of $C(last for loop counter) in new line but it doesn't work properly. It inserts rows correctly but it doesn't print $c after inserting the row. Why doesn't it work like that? And how can i update this code to work like i want?

Thanks all in advance

 <?php
   $handler = new PDO("mysql:host=localhost;dbname=test",'root','');
   $handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
   function randomname(){
     $len = mt_rand(20,50);
     $string = "";
     for($i=0;$i<$len;$i++){
       $ch = mt_rand(32, 122);
        if(($ch == 32 && $string != "") || ($ch >=97 && $ch <=122))
          $string .= chr($ch);
        else
          continue;
      }
      return $string;
   }

   function randomemail(){
     $len = mt_rand(7,15);
     $string = "";
    for($i=0;$i<$len;$i++){
         $ch = mt_rand(32, 122);
       if(($ch == 32 && $string != "") || ($ch >=97 && $ch <=122))
          $string .= chr($ch);
       else
         continue;
     }
     if($len < 10)
       return $string."@hotmail.com";
     else
       return $string."@gmail.com";
    }

    ini_set('max_execution_time', 500000);

   for($c = 0; $c<=500000;$c++){
     $name = randomname();
     $mail = randomemail();
      $query = $handler->query("insert into users(name, mail, password, created_at) values('$name', '$mail', '123132', now())");
      echo "$c</br>";
    }
raina77ow
  • 103,633
  • 15
  • 192
  • 229
B.Nabeih
  • 151
  • 1
  • 12
  • Do you mean it doesn't print $c at all, or it does print them simultaneously? Have you checked [this answer](http://stackoverflow.com/questions/3133209/how-to-flush-output-after-each-echo-call)? My understanding is that it takes too long and your browser just doesn't wait for server output - which is buffered. – raina77ow Nov 25 '16 at 17:54
  • It prints group of number ($c) every few seconds. I want it prints 1 2 3 .. etc – B.Nabeih Nov 25 '16 at 17:59

1 Answers1

0

PHP will, for performance, write once everything is finished.

If you'd like to force to flush the output buffer, you can do it by wrapping the code that should be written out at once with this code:

ob_end_flush();

// You code goes here

ob_start();

Now, every time you write something (using echo, print or similar), PHP will flush their buffers and write the output. Note that this takes a toll on performance. There are also some webservers that tries to disable this, so some weaking might be necessary.

OptimusCrime
  • 14,662
  • 13
  • 58
  • 96