db-no-async.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. <?php
  2. /**
  3. * The DB test
  4. *
  5. * @param int $queries
  6. *
  7. * @return string
  8. */
  9. function db(int $queries = 1) : string {
  10. global $pdo;
  11. if ( $queries === -1) {
  12. $statement = $pdo->prepare("SELECT id,randomNumber FROM World WHERE id=?");
  13. $statement->execute([mt_rand(1, 10000)]);
  14. return json_encode($statement->fetch(PDO::FETCH_ASSOC), JSON_NUMERIC_CHECK);
  15. }
  16. // Read number of queries to run from URL parameter
  17. $query_count = 1;
  18. if ($queries > 1) {
  19. $query_count = $queries > 500 ? 500 : $queries;
  20. }
  21. // Create an array with the response string.
  22. $arr = [];
  23. // Define query
  24. $db = $pdo->prepare('SELECT id,randomNumber FROM World WHERE id = ?');
  25. // For each query, store the result set values in the response array
  26. while ($query_count--) {
  27. $db->execute([mt_rand(1, 10000)]);
  28. $arr[] = $db->fetch(PDO::FETCH_ASSOC);
  29. }
  30. // Use the PHP standard JSON encoder.
  31. // http://www.php.net/manual/en/function.json-encode.php
  32. return json_encode($arr, JSON_NUMERIC_CHECK);
  33. }
  34. /**
  35. * The Fortunes test
  36. *
  37. * @return string
  38. */
  39. function fortunes() : string {
  40. global $pdo;
  41. $fortune = [];
  42. $db = $pdo->prepare('SELECT id, message FROM Fortune');
  43. $db->execute();
  44. $fortune = $db->fetchAll(PDO::FETCH_KEY_PAIR);
  45. $fortune[0] = 'Additional fortune added at request time.';
  46. asort($fortune);
  47. $html = '';
  48. foreach ($fortune as $id => $message) {
  49. $message = htmlspecialchars($message, ENT_QUOTES, 'UTF-8');
  50. $html .= "<tr><td>$id</td><td>$message</td></tr>";
  51. }
  52. return '<!DOCTYPE html><html><head><title>Fortunes</title></head><body><table><tr><th>id</th><th>message</th></tr>'
  53. .$html.
  54. '</table></body></html>';
  55. }
  56. /**
  57. * The Updates test
  58. *
  59. * @param int $queries
  60. *
  61. * @return string
  62. */
  63. function updates(int $queries) : string {
  64. global $pdo;
  65. $query_count = 1;
  66. if ($queries > 1) {
  67. $query_count = $queries > 500 ? 500 : $queries;
  68. }
  69. $statement = $pdo->prepare("SELECT randomNumber FROM World WHERE id=?");
  70. $update = '';
  71. while ($query_count--) {
  72. $id = mt_rand(1, 10000);
  73. $statement->execute([$id]);
  74. $world = ["id" => $id, "randomNumber" => $statement->fetchColumn()];
  75. $world['randomNumber'] = mt_rand(1, 10000);
  76. $update .="UPDATE World SET randomNumber = {$world['randomNumber']} WHERE id = $id;";
  77. $arr[] = $world;
  78. }
  79. $pdo->exec($update);
  80. return json_encode($arr, JSON_NUMERIC_CHECK);
  81. }