Mysql.php 2.3 KB

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