fetching-examples.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. <?php
  2. if (@!include __DIR__ . '/../vendor/autoload.php') {
  3. die('Install dependencies using `composer install --dev`');
  4. }
  5. Tracy\Debugger::enable();
  6. ?>
  7. <!DOCTYPE html><link rel="stylesheet" href="data/style.css">
  8. <h1>Fetching Examples | dibi</h1>
  9. <?php
  10. dibi::connect([
  11. 'driver' => 'sqlite3',
  12. 'database' => 'data/sample.s3db',
  13. ]);
  14. /*
  15. TABLE products
  16. product_id | title
  17. -----------+----------
  18. 1 | Chair
  19. 2 | Table
  20. 3 | Computer
  21. */
  22. // fetch a single row
  23. echo "<h2>fetch()</h2>\n";
  24. $row = dibi::fetch('SELECT title FROM products');
  25. Tracy\Dumper::dump($row); // Chair
  26. // fetch a single value
  27. echo "<h2>fetchSingle()</h2>\n";
  28. $value = dibi::fetchSingle('SELECT title FROM products');
  29. Tracy\Dumper::dump($value); // Chair
  30. // fetch complete result set
  31. echo "<h2>fetchAll()</h2>\n";
  32. $all = dibi::fetchAll('SELECT * FROM products');
  33. Tracy\Dumper::dump($all);
  34. // fetch complete result set like association array
  35. echo "<h2>fetchAssoc('title')</h2>\n";
  36. $res = dibi::query('SELECT * FROM products');
  37. $assoc = $res->fetchAssoc('title'); // key
  38. Tracy\Dumper::dump($assoc);
  39. // fetch complete result set like pairs key => value
  40. echo "<h2>fetchPairs('product_id', 'title')</h2>\n";
  41. $res = dibi::query('SELECT * FROM products');
  42. $pairs = $res->fetchPairs('product_id', 'title');
  43. Tracy\Dumper::dump($pairs);
  44. // fetch row by row
  45. echo "<h2>using foreach</h2>\n";
  46. $res = dibi::query('SELECT * FROM products');
  47. foreach ($res as $n => $row) {
  48. Tracy\Dumper::dump($row);
  49. }
  50. // more complex association array
  51. $res = dibi::query('
  52. SELECT *
  53. FROM products
  54. INNER JOIN orders USING (product_id)
  55. INNER JOIN customers USING (customer_id)
  56. ');
  57. echo "<h2>fetchAssoc('name|title')</h2>\n";
  58. $assoc = $res->fetchAssoc('name|title'); // key
  59. Tracy\Dumper::dump($assoc);
  60. echo "<h2>fetchAssoc('name[]title')</h2>\n";
  61. $res = dibi::query('SELECT * FROM products INNER JOIN orders USING (product_id) INNER JOIN customers USING (customer_id)');
  62. $assoc = $res->fetchAssoc('name[]title'); // key
  63. Tracy\Dumper::dump($assoc);
  64. echo "<h2>fetchAssoc('name->title')</h2>\n";
  65. $res = dibi::query('SELECT * FROM products INNER JOIN orders USING (product_id) INNER JOIN customers USING (customer_id)');
  66. $assoc = $res->fetchAssoc('name->title'); // key
  67. Tracy\Dumper::dump($assoc);