Search code examples
sqlmysqldatabaseif-statement

MySQL IF ELSE Conditions


I need a query to check the table with few conditions and return one result:

SELECT 

    IF(id='123' AND user='alex') FOUND -> return false ELSE -> return true
    IF(user='alex') NOT FOUND -> return false

FROM `table`

I have no idea on how to build such query in php function, when it call, result true or false will return

function check(id, user)
{
    $q = $mysqli->query("...sql query...");

    if($q->num_rows > 0){
        return true;
    }
    return false;
}

Solution

  • Forget about PHP code at this stage.

    Think more high-level.

    First thing you need to do is grab the right data to associate to a variable.

    Use HeidiSQL (useful, reliable tool, open-source and entirely free to use) for testing the queries within your DB.

    CASE WHEN (table.id='123' AND table.user='alex') 
           THEN 1
           ELSE 0
    END AS alexexists
    

    or the simpler:

    (table.id='123' AND table.user='alex') AS alexexists
    

    This works because TRUE is displayed as 1 in MySQL and FALSE as 0.