Mysql.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. $world = $this->world;
  33. while ($count--) {
  34. $world->execute([mt_rand(1, 10000)]);
  35. $arr[] = $world->fetch();
  36. }
  37. return $arr;
  38. }
  39. function update($request): array
  40. {
  41. $count = min(max((int) $request->get('q'), 1), 500);
  42. $arr = [];
  43. $world = $this->world;
  44. $update = $this->update;
  45. while ($count--) {
  46. $id = mt_rand(1, 10000);
  47. $world->execute([$id]);
  48. $item = $world->fetch();
  49. $update->execute(
  50. [$item['randomNumber'] = mt_rand(1, 10000), $id]
  51. );
  52. $arr[] = $item;
  53. }
  54. return $arr;
  55. }
  56. function fortune(): string
  57. {
  58. $this->fortune->execute();
  59. $arr = $this->fortune->fetchAll(PDO::FETCH_KEY_PAIR);
  60. $arr[0] = 'Additional fortune added at request time.';
  61. asort($arr);
  62. $html = '';
  63. foreach ($arr as $id => $message) {
  64. $message = htmlspecialchars($message, ENT_QUOTES, 'UTF-8');
  65. $html .= "<tr><td>$id</td><td>$message</td></tr>";
  66. }
  67. return "<!DOCTYPE html><html><head><title>Fortunes</title></head><body><table><tr><th>id</th><th>message</th></tr>$html</table></body></html>";
  68. }
  69. }