I am building an SQL Library for my framework which I am making for a university project. I have finished all the helper methods and I am confused about one thing.
How do I bind a parameter or value in a Having clause where the left hand side argument is an aggregate function and the right hand side argument is a variable?
I have created helper methods which take associative arrays and format them ready for prepared statements so all I have to do is execute,
Please see the last example below with the having clause, when the left hand side argument is an aggregate function and the right hand side is a variable, how could I set a parameter to bind by value/param?
Also as a side question, is it possible to have BOTH bindparam and bind value in the same stmt?
Any advice would be helpful and please do let me know if there is a better way, I know I could always just change it around but I would prefer to have this option
public function test_having()
{
$query = new Query();
$query
->select('name','age','height')
->from('Person')
->where('id','=',33)
->having('name','>',9867);
//Works perfectly
$this->assertEqualsIgnoringCase(
"SELECT name,age,height FROM Person WHERE id = :id HAVING name > :name ",
$query->get_query()
);
}
public function test_having_with_left_hand_side_aggregage_function($value='')
{
$query = new Query();
$height = 220;
$query
->select('max(age) as max_age','person')
->from('Person')
->where('age','>',50)
->group_by('max_age, person')
->having('max(height)','>',$height);
$this->assertEqualsIgnoringCase(
"SELECT max(age) as max_age,person
FROM Person WHERE age > :age GROUP BY max_age,person
//Not sure if this is a valid prepared stmt?:
HAVING count(reviews) > :count(reviews) ",
$query->get_query()
);
}
I have a helper method which loops through arrays and passes the key, value, and operand to a method which adds these to an array, Now the parameters are properly set, im just not sure how can I bind a variable to an aggregate method?
protected static function set_stmt($key, $op, $value, $logic_ops='')
{
if (is_object($value) && $value instanceof Query) {
$subquery = self::sort_subquery($value);
$stmt = $subquery['query'];
$stmt = ($logic_ops != '') ?
"$key $op $stmt $logic_ops " :
"$key $op $stmt ";
$result = [
'stmt' => $stmt,
'exec' => $subquery['exec'],
'params' => $subquery['params']
];
}else{
$params[$key] = ['key' => ":$key", 'value' => $value];
$stmt = ($logic_ops != '') ?
"$key $op :$key $logic_ops " :
"$key $op :$key ";
$result = [
'stmt' => $stmt,
'params' => $params,
];
}
return $result;
}