I'm trying to build a function that takes 2 parameters : a table name and a list of params and build a SELECT query.
Here's an example :
$params['user'] = 'myTestUsername';
$params['pass'] = 'myTestPassword';
echo $dbCon->countBy('users', $params);
This should build (and execute) this query :
SELECT * FROM users WHERE user='myTestUsername' AND pass='myTestPassword'
and then returns the number of selected rows...
I have these 2 methods :
1) the main method (where the SQL magic should happen) :
public function countBy($table, $params) {
$query = $this->buildQuery($table, $params);
$mySelect = $this->dbh->prepare($query);
$params = array_merge(array(count($params)), array_values($params));
call_user_func_array(array(&$mySelect, 'bind_param'), $params);
if ($mySelect) {
$mySelect->execute();
return $mySelect->rowCount();
}
return 0;
}
2) the method that builds the query with the given parameters :
public function buildQuery($table, $params) {
$i = 0;
$where = '';
if (count($params) > 0) {
$query = 'SELECT * FROM ' . $table . ' WHERE ';
foreach(array_keys($params) as $pList) {
$i++;
$where .= $pList . '=?' . ($i<count($params) ? ' AND ' : '') ;
}
$query .= $where;
// output is like : SELECT * FROM users WHERE user=? AND pass=?
return $query;
}
return null;
}
The 2nd method works great, but I have some issues at the 1st one. And it's related to the use of the "call_user_func_array" method.
I really don't see what I did wrong... Any ideas?
The "solution" with call_user_func_array was taken from here, but I'm not sure about this part :
$params = array_merge(array(str_repeat('s', count($params))), array_values($params));
In my code I tried using it like this :
$params = array_merge(array(count($params)), array_values($params));
but still nothing...