1
0
mirror of https://github.com/dg/dibi.git synced 2025-01-17 06:08:19 +01:00
php-dibi/examples/query-language-and-conditions.php

67 lines
1.2 KiB
PHP
Raw Permalink Normal View History

2017-07-21 21:34:37 +02:00
<?php
declare(strict_types=1);
?>
2010-08-03 12:28:07 +02:00
<!DOCTYPE html><link rel="stylesheet" href="data/style.css">
2018-05-10 21:45:11 +02:00
<h1>Query Language & Conditions | Dibi</h1>
2010-08-03 12:28:07 +02:00
2008-07-17 03:51:29 +00:00
<?php
if (@!include __DIR__ . '/../vendor/autoload.php') {
die('Install packages using `composer install`');
}
2008-07-17 03:51:29 +00:00
2018-04-17 10:03:43 +02:00
$dibi = new Dibi\Connection([
'driver' => 'sqlite',
2012-12-16 19:31:37 +01:00
'database' => 'data/sample.s3db',
2015-10-06 01:39:01 +02:00
]);
2008-07-17 03:51:29 +00:00
2010-08-03 11:48:51 +02:00
// some variables
$cond1 = true;
$cond2 = false;
2008-07-17 03:51:29 +00:00
$foo = -1;
$bar = 2;
2010-08-03 11:48:51 +02:00
// conditional variable
$name = $cond1 ? 'K%' : null;
2008-07-17 03:51:29 +00:00
// if & end
2018-04-17 10:03:43 +02:00
$dibi->test('
2010-08-03 11:48:51 +02:00
SELECT *
FROM customers
2021-03-01 17:55:56 +01:00
%if', isset($name), 'WHERE name LIKE ?', $name, '%end',
2008-07-17 03:51:29 +00:00
);
// -> SELECT * FROM customers WHERE name LIKE 'K%'
2008-10-28 02:06:55 +00:00
2008-07-17 03:51:29 +00:00
// if & else & (optional) end
2018-04-17 10:03:43 +02:00
$dibi->test('
2010-08-03 11:48:51 +02:00
SELECT *
FROM people
WHERE id > 0
2015-06-19 03:11:36 +02:00
%if', ($foo > 0), 'AND foo=?', $foo, '
%else %if', ($bar > 0), 'AND bar=?', $bar, '
');
// -> SELECT * FROM people WHERE id > 0 AND bar=2
2008-10-28 02:06:55 +00:00
2008-07-17 03:51:29 +00:00
// nested condition
2018-04-17 10:03:43 +02:00
$dibi->test('
2010-08-03 11:48:51 +02:00
SELECT *
FROM customers
2010-08-03 11:48:51 +02:00
WHERE
%if', isset($name), 'name LIKE ?', $name, '
%if', $cond2, 'AND admin=1 %end
2021-03-01 17:55:56 +01:00
%else 1 LIMIT 10 %end',
2008-07-17 03:51:29 +00:00
);
// -> SELECT * FROM customers WHERE LIMIT 10
2012-12-16 19:31:37 +01:00
// IF()
2018-04-17 10:03:43 +02:00
$dibi->test('UPDATE products SET', [
'price' => $dibi->expression('IF(price_fixed, price, ?)', 123),
2015-10-06 01:39:01 +02:00
]);
2012-12-16 19:31:37 +01:00
// -> SELECT * FROM customers WHERE LIMIT 10