php - Laravel 5.8 conditionally inserting sql snippet
I'm trying to figure out the best way to resolve inserting a conditional sql snippet within a laravel 5.8 application function.
I'm successfully calling a function with a request parameter$type
.
$type
coming into this function can be 1,2 or 3 (when 3 I basically want the sql query to perform with nothing in that spot), but currently it successfully returns the query results from below as if nothing is being injected at all. I can dump the $typeCondition based on the selection and it toggles properly, so I know the typeCondition is being set properly but it looks like it's not actually plugging the typeCondition into the query and I get the same results every time, so it seems like maybe this is a syntax issue?
If I run the below version as just:typeCondition
it errors out and says it's not a valid param call.
What should I do here?
public static function gatherReporting($type) {
if($type ==1){
$typeCondition = 'AND T1 . parent_id IS NOT NULL';
}elseif($type ==2){
$typeCondition = 'AND T1 . parent_id IS NULL';
}else{
$typeCondition = '';
}
$sql = "
SELECT *
FROM SCHEMA . TABLE T1
WHERE ACTIVE = 1
{:typeCondition}
INNER JOIN SCHEMA . TABLE2 T2
ON T1.ID = T2.ID
";
return DB::connection('odbc')->select($sql, [
'typeCondition' => $typeCondition
]);
}
Answer
Solution:
You can treat the query as a
string
and concatenate it with your variable. Like so:Answer
Solution:
You can use Query Builder to get something clean :