php - Laravel 5.8 conditionally inserting sql snippet

150

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
            ]);
}
147

Answer

Solution:

You can treat the query as astring and concatenate it with your variable. Like so:

$sql = "SELECT * FROM SCHEMA . TABLE T1 WHERE ACTIVE = 1" . $typeCondition . "INNER JOIN SCHEMA . TABLE2 T2 ON T1.ID = T2.ID";
652

Answer

Solution:

You can use Query Builder to get something clean :

$query = Schema::select('*')->where('active', 1);

if ($type === 1) {
    $query->whereNotNull('parent_id');
} elseif ($type === 2) {
    $query->whereNull('parent_id');
}

$data = $query->get();

People are also looking for solutions to the problem: How to define env values that start with dollar sign in php-fpm

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.