Mysql.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. class Mysql
  3. {
  4. protected PDO $pdo;
  5. protected PDOStatement $world;
  6. protected PDOStatement $fortune;
  7. protected PDOStatement $update;
  8. public function __construct()
  9. {
  10. $this->pdo = new PDO(
  11. 'mysql:host=tfb-database;dbname=hello_world',
  12. 'benchmarkdbuser',
  13. 'benchmarkdbpass',
  14. [
  15. PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
  16. PDO::ATTR_EMULATE_PREPARES => false
  17. ]
  18. );
  19. $this->world = $this->pdo->prepare('SELECT id,randomNumber FROM World WHERE id=?');
  20. $this->fortune = $this->pdo->prepare('SELECT id,message FROM Fortune');
  21. $this->update = $this->pdo->prepare('UPDATE World SET randomNumber=? WHERE id=?');
  22. }
  23. function db(): array
  24. {
  25. $this->world->execute([mt_rand(1, 10000)]);
  26. return $this->world->fetch();
  27. }
  28. function query($request): array
  29. {
  30. $count = min(max((int) $request->get('q'), 1), 500);
  31. $arr = [];
  32. while ($count--) {
  33. $this->world->execute([mt_rand(1, 10000)]);
  34. $arr[] = $this->world->fetch();
  35. }
  36. return $arr;
  37. }
  38. function update($request): array
  39. {
  40. $count = min(max((int) $request->get('q'), 1), 500);
  41. $arr = [];
  42. while ($count--) {
  43. $id = mt_rand(1, 10000);
  44. $this->world->execute([$id]);
  45. $item = $this->world->fetch();
  46. $this->update->execute(
  47. [$item['randomNumber'] = mt_rand(1, 10000), $id]
  48. );
  49. $arr[] = $item;
  50. }
  51. return $arr;
  52. }
  53. function fortune(): string
  54. {
  55. $this->fortune->execute();
  56. $arr = $this->fortune->fetchAll(PDO::FETCH_KEY_PAIR);
  57. $arr[0] = 'Additional fortune added at request time.';
  58. asort($arr);
  59. $html = '';
  60. foreach ($arr as $id => $message) {
  61. $message = htmlspecialchars($message, ENT_QUOTES, 'UTF-8');
  62. $html .= "<tr><td>$id</td><td>$message</td></tr>";
  63. }
  64. return "<!DOCTYPE html><html><head><title>Fortunes</title></head><body><table><tr><th>id</th><th>message</th></tr>$html</table></body></html>";
  65. }
  66. }