Advertisement
Guest User

Untitled

a guest
Aug 1st, 2013
318
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.58 KB | None | 0 0
  1. <?php
  2.  
  3. function out($line = '')
  4. {
  5.     echo PHP_EOL.$line.PHP_EOL;
  6. }
  7.  
  8. function sep()
  9. {
  10.     out();
  11.     out('------------------------------');
  12.     out();
  13. }
  14.  
  15. /**
  16.  * @param $pdo PDO
  17.  * @param $config array
  18.  */
  19. function run($pdo, $config)
  20. {
  21.     $sql = "TRUNCATE products";
  22.  
  23.     $stmt = $pdo->prepare($sql);
  24.     $stmt->execute();
  25.  
  26.     $numberOfInsertOps = $config['insert_number'];
  27.  
  28.     $startInsertTime = microtime(true);
  29.  
  30.     $sql = "INSERT INTO products (name, price) VALUES (:name, :price)";
  31.     $stmt = $pdo->prepare($sql);
  32.  
  33.     for ($i = 0; $i < $numberOfInsertOps; $i++)
  34.     {
  35.         $name = md5(rand(0, 1000));
  36.         $price = rand(1, 1000);
  37.  
  38.         $stmt->bindParam(':name', $name);
  39.         $stmt->bindParam(':price', $price);
  40.  
  41.         try
  42.         {
  43.             $result = $stmt->execute();
  44.  
  45.             if (!$result)
  46.             {
  47.                 out('shit happened');
  48.  
  49.                 $hostname = 'localhost';
  50.                 $username = 'root';
  51.                 $password = 'root';
  52.                 $db_name = 'test';
  53.  
  54.                 $pdo = new PDO("mysql:host=$hostname;dbname=$db_name", $username, $password);
  55.                 $sql = "INSERT INTO products (name, price) VALUES (:name, :price)";
  56.                 $stmt = $pdo->prepare($sql);
  57.  
  58.                 $stmt->bindParam(':name', $name);
  59.                 $stmt->bindParam(':price', $price);
  60.  
  61.                 $result = $stmt->execute();
  62.  
  63.                 if (!$result)
  64.                 {
  65.                     out('double shit');
  66.                 }
  67.  
  68.             }
  69.  
  70.             out($pdo->lastInsertId());
  71.         }
  72.         catch (Exception $e)
  73.         {
  74.             sep($e->getMessage());
  75.         }
  76.     }
  77.  
  78.     out('Insert in one query time: ' . ( microtime(true) - $startInsertTime) );
  79. }
  80.  
  81.  
  82. $pdo = new PDO("mysql:host=$hostname;dbname=$db_name", $username, $password);
  83.  
  84. run($pdo, array(
  85.     'insert_number' => 100
  86. ));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement