query-language-basic-examples.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <?php
  2. declare(strict_types=1);
  3. ?>
  4. <!DOCTYPE html><link rel="stylesheet" href="data/style.css">
  5. <h1>Query Language Basic Examples | Dibi</h1>
  6. <?php
  7. if (@!include __DIR__ . '/../vendor/autoload.php') {
  8. die('Install packages using `composer install`');
  9. }
  10. date_default_timezone_set('Europe/Prague');
  11. $dibi = new Dibi\Connection([
  12. 'driver' => 'sqlite',
  13. 'database' => 'data/sample.s3db',
  14. ]);
  15. // SELECT
  16. $ipMask = '192.168.%';
  17. $timestamp = mktime(0, 0, 0, 10, 13, 1997);
  18. $dibi->test('
  19. SELECT COUNT(*) as [count]
  20. FROM [comments]
  21. WHERE [ip] LIKE ?', $ipMask, '
  22. AND [date] > ', new Dibi\DateTime($timestamp)
  23. );
  24. // -> SELECT COUNT(*) as [count] FROM [comments] WHERE [ip] LIKE '192.168.%' AND [date] > 876693600
  25. // dibi detects INSERT or REPLACE command
  26. $dibi->test('
  27. REPLACE INTO products', [
  28. 'title' => 'Super product',
  29. 'price' => 318,
  30. 'active' => true,
  31. ]);
  32. // -> REPLACE INTO products ([title], [price], [active]) VALUES ('Super product', 318, 1)
  33. // multiple INSERT command
  34. $array = [
  35. 'title' => 'Super Product',
  36. 'price' => 12,
  37. 'brand' => null,
  38. 'created' => new DateTime,
  39. ];
  40. $dibi->test('INSERT INTO products', $array, $array, $array);
  41. // -> INSERT INTO products ([title], [price], [brand], [created]) VALUES ('Super Product', ...) , (...) , (...)
  42. // dibi detects UPDATE command
  43. $dibi->test('
  44. UPDATE colors SET', [
  45. 'color' => 'blue',
  46. 'order' => 12,
  47. ], '
  48. WHERE id=?', 123);
  49. // -> UPDATE colors SET [color]='blue', [order]=12 WHERE id=123
  50. // modifier applied to array
  51. $array = [1, 2, 3];
  52. $dibi->test('
  53. SELECT *
  54. FROM people
  55. WHERE id IN (?)', $array
  56. );
  57. // -> SELECT * FROM people WHERE id IN ( 1, 2, 3 )
  58. // modifier %by for ORDER BY
  59. $order = [
  60. 'field1' => 'asc',
  61. 'field2' => 'desc',
  62. ];
  63. $dibi->test('
  64. SELECT *
  65. FROM people
  66. ORDER BY %by', $order, '
  67. ');
  68. // -> SELECT * FROM people ORDER BY [field1] ASC, [field2] DESC
  69. // indentifiers and strings syntax mix
  70. $dibi->test('UPDATE [table] SET `item` = "5 1/4"" diskette"');
  71. // -> UPDATE [table] SET [item] = '5 1/4" diskette'