ra_controller.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. <?php
  2. class RaController extends AppController
  3. {
  4. protected $pdo;
  5. protected function before_filter()
  6. {
  7. View::select(null, null);
  8. header('Content-Type: application/json');
  9. $this->pdo = new PDO('mysql:host=tfb-database;dbname=hello_world', 'benchmarkdbuser', 'benchmarkdbpass', [
  10. PDO::ATTR_PERSISTENT => true
  11. ]);
  12. }
  13. public function index()
  14. {
  15. $statement = $this->pdo->query( 'SELECT * FROM World WHERE id='. mt_rand(1, 10000) );
  16. echo json_encode($statement->fetch(PDO::FETCH_ASSOC));
  17. }
  18. public function query($count = 1)
  19. {
  20. $count = min(max($count, 1), 500);
  21. $res = $this->pdo->prepare('SELECT * FROM World WHERE id=?');
  22. while ($count--) {
  23. $res->execute([mt_rand(1, 10000)]);
  24. $worlds[] = $res->fetch(PDO::FETCH_ASSOC);
  25. }
  26. echo json_encode($worlds);
  27. }
  28. public function update($count = 1)
  29. {
  30. $count = min(max($count, 1), 500);
  31. $this->pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
  32. $sth = $this->pdo->prepare('SELECT randomNumber FROM World WHERE id=?');
  33. $updateStatement = $this->pdo->prepare('UPDATE World SET randomNumber=? WHERE id=?');
  34. while ($count--) {
  35. $id = mt_rand(1, 10000);
  36. $sth->execute([$id]);
  37. $row = ['id' => $id, 'randomNumber' => $sth->fetchColumn()];
  38. $updateStatement->execute(
  39. [$row['randomNumber'] = mt_rand(1, 10000), $id]
  40. );
  41. $worlds[] = $row;
  42. }
  43. echo json_encode($worlds);
  44. }
  45. }