Skip to content

Instantly share code, notes, and snippets.

@fangel
Created April 6, 2010 08:39
Show Gist options
  • Save fangel/357365 to your computer and use it in GitHub Desktop.
Save fangel/357365 to your computer and use it in GitHub Desktop.
<?php
namespace sqlparser\utils;
function perform_select( $sql, $tabel, $bindings = false) {
$tree = \sqlparser\parse($sql);
if( get_class($tree) != 'sqlparser\tree\Select') throw new \sqlparser\Exception('Cannont perform non-selects with perform_select');
if( $bindings ) list($tree,,) = \sqlparser\bind_values($tree, $bindings);
return array_map( function($row) use ($tree) {
return \sqlparser\project($tree, $row);
}, array_filter($tabel, function($row) use ($tree) {
return \sqlparser\test_where($tree, $row);
}));
}
:: RESULT ::
Performing the following SQL: SELECT id, b AS long_b FROM b WHERE a = :a AND b > :b (with bindings: a=1&b=3)
On the following table:
+----+---+------+
| id | a | b |
+----+---+------+
| 1 | 1 | 1 |
| 2 | 1 | 2 |
| 3 | 1 | 3 |
| 4 | 1 | 4 |
| 5 | 1 | 5 |
| 6 | 2 | 1 |
| 7 | 2 | 2 |
| 8 | 2 | 3 |
| 9 | 1 | 6323 |
+----+---+------+
Result:
+----+--------+
| id | long_b |
+----+--------+
| 4 | 4 |
| 5 | 5 |
| 9 | 6323 |
+----+--------+
<?php
include 'SqlParser/SqlParser.php';
include 'Utils/Utils.php';
$sql = 'SELECT id, b AS long_b FROM b WHERE a = :a AND b > :b';
$bindings = array('a'=>1, 'b'=>3);
$tbl = array(
array('id'=>1, 'a'=>1, 'b'=>1),
array('id'=>2, 'a'=>1, 'b'=>2),
array('id'=>3, 'a'=>1, 'b'=>3),
array('id'=>4, 'a'=>1, 'b'=>4),
array('id'=>5, 'a'=>1, 'b'=>5),
array('id'=>6, 'a'=>2, 'b'=>1),
array('id'=>7, 'a'=>2, 'b'=>2),
array('id'=>8, 'a'=>2, 'b'=>3),
array('id'=>9, 'a'=>1, 'b'=>6323)
);
echo 'Performing the following SQL: ' . $sql . ' (with bindings: ' . http_build_query($bindings) . ')' . "\n";
echo 'On the following table:' . "\n";
echo bach\utils\print_table($tbl) . "\n";
$res = sqlparser\utils\perform_select($sql, $tbl, $bindings);
echo 'Result:' . "\n";
echo bach\utils\print_table($res);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment