0

I want to insert an if/else condition inside my sql request. How do I do this? I have tried this below, but it doesn't work:

     $QpageManagerGeneralCondition = $OSCOM_PDO->prepare('
         select pmd.pages_html_text,
         pm.page_general_condition
         from :table_pages_manager pm,
         :table_pages_manager_description pmd
          where
         if (pm.customers_group_id = :customers_group_id) else (pm.customers_group_id = 99)

         and pm.page_general_condition = 1
         and pmd.language_id = :language_id
         and pmd.pages_id = pm.pages_id
         limit 1
          ');
     $QpageManagerGeneralCondition->bindInt(':language_id',(int)$_SESSION['languages_id'] );
     $QpageManagerGeneralCondition->bindInt(':customers_group_id',$OSCOM_Customer->getCustomersGroupID() );

     $QpageManagerGeneralCondition->execute();
     $QpageManagerGeneralCondition->value('pages_html_text');
Nathaniel Ford
  • 20,545
  • 20
  • 91
  • 102
kakashi
  • 23
  • 1
  • 6

2 Answers2

0

I think you are looking for a CASE statement. For example, you can use a case statement to have different values for a column 'is_a_senior'. In this example if the year = 'SR' then the column 'is_a_senior' gets a value of yes.

SELECT player_name,
   year,
   CASE WHEN year = 'SR' THEN 'yes'
        ELSE 'no' END AS is_a_senior
FROM benn.college_football_players

see https://sqlschool.modeanalytics.com/intermediate/case/

--

For your specific example it looks like you might not actually need a conditional though and adding a default value to your query might be enough.

ISNULL(pm.customers_group_id, 99)  AS pm.customers_group_id

If you need more than just an ISNULL check also take a look at the COALESCE keyword. COALESCE is a pretty powerful command and lets you add a subquery into your query conditionally if the null check finds null.

pwilmot
  • 586
  • 2
  • 8
0

I see you are using PHP/PDO in order to query your database, you could just use the conditional expression in php (instead of in SQL) and edit the query depending on which side of the if gets executed. Which is probably faster.

Conditional expressions are also a option. Referring to this question for that.

Can you have if-then-else logic in SQL?

Community
  • 1
  • 1
LaurensVijnck
  • 532
  • 6
  • 20