phpmysqldatabaseif-statementselect-query

PHP/MySql if-operator within select statement


I have database with several tables, all have one column with same name. I want to fetch data from this column that way so when it's fetched from particular table ("countries"), it has string append, otherwise data is simply fetched. Here is my method

public function getInfo($table, $id) {
    $operate = $this->pdo->prepare("select if({$table}=='countries', 'concat('capital', city)', 'city') city from {$table} where id= {$id}");
        $operate->execute();

        return $operate->fetchObject();
    }

I have several methods within a class and everything works fine. This one also works without if-statement, the problem appears to be with this expression: {$table}=='countries'. However, I couldn't find where my mistake is. I'm new to php and would be glad to know what is the problem with this expression and how shall I get around it.


Solution

  • Unfortunatly the ${}-way of string-interpolation in PHP only supports one expression like getting a value from an array. It is not possible to use an if-statement or the ternary operator inside this construct.

    This would be an option:

    $column = ($table == 'countries')? "concat('capital',city)":"city";
    $operate = this->pdo->prepare("select $column from {$table} where id= {$id}");