If you are creating such a complicated function, why don't you check first the returning values?
I did this test
function SelectQuery2($table, array $where) {
$sql = "SELECT * FROM `$table` ";
$values = null;
if ($where) {
$sql .= "WHERE " . implode(" AND ", array_map(function ($c) { return "`$c` = ?"; }, array_keys($where)));
$values = array_values($where);
}
return array($sql, $values);
}
$where = array("ticketnumber = asdasdasd", "ticketbla = dfgdfgdfg");
$ticket=SelectQuery2("tickets", $where);
var_dump($ticket);
And the output is:
array (size=2)
0 => string 'SELECT * FROM `tickets` WHERE `0` = ? AND `1` = ?' (length=49)
1 =>
array (size=2)
0 => string 'ticketnumber = asdasdasd' (length=26)
1 => string 'ticketbla = dfgdfgdfg' (length=21)
So, are you expecting your column names to be 0
and 1
, instead of the real column names?
I guess - no. You need array_keys()
in the closure, but you are passing array $where
as numeric array (with only values), so the keys are 0
, 1
, etc...
You would need an associative array, which passes the column name as key
because the closure requires it this way, and the value as value
because the PDOStatement::execute
requires it this way, when not using named placeholders, but ?
.
http://www.php.net/manual/en/pdostatement.execute.php
The appropriate example from here is:
<?php
/* Execute a prepared statement by passing an array of insert values */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < ? AND colour = ?');
$sth->execute(array($calories, $colour));
?>
Which says that execute()
here accepts the values 150
and red
as array values (array(150, 'red')
) which in your case will be (array($_GET["seq"])
).
The right example of the passed array should be:
$where = array('ticketnumber' => $_GET["seq"]);
If you need multiple column names and values, just add more key => value pairs.
$where = array(
'ticketnumber' => $_GET["seq"],
'ticket_owner' => $_GET['owner'],
'ticket_etc' => $_GET['etc']
);
But, here you have some disadvantages:
Your function is strictly complicated to rules col1 = val1 AND col2 = val2 AND...
. Your SELECT query is only for simple data extraction. You barely can use SQL functions, HAVING clauses, date operators, BETWEEN, nor <
; >
.
That's why I would not suggest this variant of wrapping PDO. At its nature, PDO is already some kind of wrapper. At least don't make the query string dynamic. You can try to wrap the prepare()
, execute()
, fetch()
, but stop there. Also don't do it in procedural PHP functions. It will just increase the agony of bad design, such as using globals, because your PDO object is not shared between them.