Skip to content

Commit a6f3e05

Browse files
committed
ups
1 parent 5e193ce commit a6f3e05

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed

MysqliDb.php

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -215,6 +215,48 @@ public function rawQuery($query, $bindParams = null)
215215
return $this->_dynamicBindResults($stmt);
216216
}
217217

218+
/**
219+
* Pass in an array of subqueries for union query construction.
220+
*
221+
* @param array $objects Contains a user-provided array of subqueries
222+
* @param $type 'ALL', 'DISTINCT', null.
223+
*
224+
* @return array Contains the returned rows from the query.
225+
*/
226+
public function union ($objects, $type = null)
227+
{
228+
$allowedTypes = array('ALL', 'DISTINCT');
229+
$type = strtoupper (trim ($type));
230+
231+
if ($type && !in_array ($type, $allowedTypes))
232+
die ('Wrong UNION type: '.$type);
233+
234+
if (!is_array ($objects))
235+
return;
236+
237+
$this->_query = "";
238+
$i = 0;
239+
foreach ($objects as $obj) {
240+
if (!is_object ($obj))
241+
continue;
242+
243+
if ($i++ != 0)
244+
$this->_query .= " UNION {$type} ";
245+
246+
$subQuery = $obj->getSubQuery();
247+
$this->_query .= "(" . $subQuery['query'] . ")";
248+
foreach ($subQuery['params'] as $v)
249+
$this->_bindParam ($v);
250+
}
251+
$stmt = $this->_buildQuery (null);
252+
$stmt->execute();
253+
$this->_stmtError = $stmt->error;
254+
$this->reset();
255+
256+
return $this->_dynamicBindResults($stmt);
257+
}
258+
259+
218260
/**
219261
*
220262
* @param string $query Contains a user-provided select query.

readme.md

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -260,6 +260,21 @@ $data = Array (
260260
$id = $db->insert ("products", $data);
261261
// Gives INSERT INTO PRODUCTS (productName, userId, lastUpdated) values ("test product", (SELECT name FROM users WHERE id = 6), NOW());
262262
```
263+
UNION queries
264+
```php
265+
$common = $db->subQuery();
266+
$common->where ("agentId", 10);
267+
268+
$customers = $common->copy();
269+
$customers->get ("customers");
270+
271+
$users = $common->copy();
272+
$users->get ("users");
273+
274+
$db->orderBy ("lastModified");
275+
$res = $db->union (Array ($customers, $users, $companies), "ALL");
276+
GIVES (SELECT * FROM customers WHERE agentId = 10 ) UNION ALL (SELECT * FROM users WHERE agentId = 10 ) ORDER BY lastModified DESC
277+
```
263278
### Helper commands
264279
Reconnect in case mysql connection died
265280
```php

0 commit comments

Comments
 (0)