app.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. $pdo = new PDO('mysql:host=tfb-database;dbname=hello_world', 'benchmarkdbuser', 'benchmarkdbpass',
  3. [PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
  4. PDO::ATTR_EMULATE_PREPARES => false]
  5. );
  6. $statement = $pdo->prepare('SELECT id,randomNumber FROM World WHERE id=?');
  7. $fortune = $pdo->prepare('SELECT id,message FROM Fortune');
  8. $random = $pdo->prepare('SELECT randomNumber FROM World WHERE id=?');
  9. $update = $pdo->prepare('UPDATE World SET randomNumber=? WHERE id=?');
  10. function db()
  11. {
  12. global $statement;
  13. ngx_header_set('Content-Type', 'application/json');
  14. $statement->execute([mt_rand(1, 10000)]);
  15. echo json_encode($statement->fetch(), JSON_NUMERIC_CHECK);
  16. }
  17. function query()
  18. {
  19. global $statement;
  20. ngx_header_set('Content-Type', 'application/json');
  21. $query_count = 1;
  22. $params = ngx::query_args()['queries'];
  23. if ($params > 1) {
  24. $query_count = min($params, 500);
  25. }
  26. while ($query_count--) {
  27. $statement->execute([mt_rand(1, 10000)]);
  28. $arr[] = $statement->fetch();
  29. }
  30. echo json_encode($arr, JSON_NUMERIC_CHECK);
  31. }
  32. function update()
  33. {
  34. global $pdo, $random, $update;
  35. ngx_header_set('Content-Type', 'application/json');
  36. $query_count = 1;
  37. $params = ngx::query_args()['queries'];
  38. if ($params > 1) {
  39. $query_count = min($params, 500);
  40. }
  41. while ($query_count--) {
  42. $id = mt_rand(1, 10000);
  43. $random->execute([$id]);
  44. $world = ['id' => $id, 'randomNumber' => $random->fetchColumn()];
  45. $update->execute(
  46. [$world['randomNumber'] = mt_rand(1, 10000), $id]
  47. );
  48. $arr[] = $world;
  49. }
  50. // $pdo->beginTransaction();
  51. // foreach($arr as $world) {
  52. // $update->execute([$world['randomNumber'], $world['id']]);
  53. // }
  54. // $pdo->commit();
  55. echo json_encode($arr, JSON_NUMERIC_CHECK);
  56. }
  57. function fortune()
  58. {
  59. global $fortune;
  60. ngx_header_set('Content-Type', 'text/html;charset=UTF-8');
  61. $fortune->execute();
  62. $arr = $fortune->fetchAll(PDO::FETCH_KEY_PAIR);
  63. $arr[0] = 'Additional fortune added at request time.';
  64. asort($arr);
  65. $html = '';
  66. foreach ($arr as $id => $message) {
  67. $message = htmlspecialchars($message, ENT_QUOTES, 'UTF-8');
  68. $html .= "<tr><td>$id</td><td>$message</td></tr>";
  69. }
  70. echo '<!DOCTYPE html><html><head><title>Fortunes</title></head><body><table><tr><th>id</th><th>message</th></tr>',
  71. $html,
  72. '</table></body></html>';
  73. }