1
0
mirror of https://github.com/dg/dibi.git synced 2025-02-24 19:02:36 +01:00
php-dibi/examples/sql-builder.php

91 lines
1.8 KiB
PHP
Raw Normal View History

2008-07-17 03:51:29 +00:00
<style>
pre.dibi { padding-bottom: 10px; }
</style>
<h1>dibi SQL builder example</h1>
<pre>
<?php
require_once 'Nette/Debug.php';
2008-07-17 03:51:29 +00:00
require_once '../dibi/dibi.php';
// required since PHP 5.1.0
date_default_timezone_set('Europe/Prague');
dibi::connect(array(
'driver' => 'sqlite',
'database' => 'sample.sdb',
));
// dibi detects INSERT or REPLACE command
dibi::test('
2008-10-28 02:06:55 +00:00
REPLACE INTO [products]', array(
'title' => 'Super product',
'price' => 318,
'active' => TRUE,
2008-07-17 03:51:29 +00:00
));
2008-10-28 02:06:55 +00:00
// -> REPLACE INTO [products] ([title], [price], [active]) VALUES ('Super product', 318, 1)
2008-07-17 03:51:29 +00:00
// multiple INSERT command
$array = array(
'title' => 'Super Product',
'price' => 12,
'brand' => NULL,
'created' => dibi::datetime(),
);
dibi::test("INSERT INTO [products]", $array, $array, $array);
2008-10-28 02:06:55 +00:00
// -> INSERT INTO [products] ([title], [price], [brand], [created]) VALUES ('Super Product', ...) , (...) , (...)
2008-07-17 03:51:29 +00:00
// dibi detects UPDATE command
dibi::test("
2008-10-28 02:06:55 +00:00
UPDATE [colors] SET", array(
'color' => 'blue',
'order' => 12,
), "
WHERE [id]=%i", 123);
// -> UPDATE [colors] SET [color]='blue', [order]=12 WHERE [id]=123
2008-07-17 03:51:29 +00:00
// SELECT
$ipMask = '192.168.%';
$timestamp = mktime(0, 0, 0, 10, 13, 1997);
dibi::test('
2008-10-28 02:06:55 +00:00
SELECT COUNT(*) as [count]
FROM [comments]
WHERE [ip] LIKE %s', $ipMask, '
AND [date] > ', dibi::date($timestamp)
2008-07-17 03:51:29 +00:00
);
2008-10-28 02:06:55 +00:00
// -> SELECT COUNT(*) as [count] FROM [comments] WHERE [ip] LIKE '192.168.%' AND [date] > 876693600
2008-07-17 03:51:29 +00:00
// IN array
$array = array(1, 2, 3);
dibi::test("
2008-10-28 02:06:55 +00:00
SELECT *
FROM [people]
WHERE [id] IN (", $array, ")
2008-07-17 03:51:29 +00:00
");
2008-10-28 02:06:55 +00:00
// -> SELECT * FROM [people] WHERE [id] IN ( 1, 2, 3 )
// ORDER BY array
$order = array(
'field1' => 'asc',
'field2' => 'desc',
);
dibi::test("
SELECT *
FROM [people]
ORDER BY %by", $order, "
");
2008-10-28 02:06:55 +00:00
// -> SELECT * FROM [people] ORDER BY [field1] ASC, [field2] DESC