Adam
Adam

Reputation: 20882

MYSQL PHP PDO - Adding WHERE PlaceHolder Clauses on the fly

I need to insert a MySQL WHERE Condition as a placeholder in PDO. The condition depends on your preference of gender (social site) - below creates to WHERE condition code:

    if($_SESSION['interestedMales'] && $_SESSION['interestedFemales']) {
        return '(a.profile_gender=0 OR a.profile_gender=1)';
    }elseif($_SESSION['interestedMales']) {
        return '(a.profile_gender=1)';
    }elseif($_SESSION['interestedFemales']) {
        return '(a.profile_gender=0)';
    }else{
  return '(a.profile_gender='.$_SESSION['gender'].')';
    }

returns into variable - $pdoGenderCondition

Next I'm adding this to a PHP PDO statement:

    $sql='SELECT a.userinfo
                FROM login AS a
                WHERE a.photoidvisible=1  AND ? LIMIT 9;';
    echo $sql;
    $pds=$database_users->pdo->prepare($sql); $pds->execute(array($pdoGenderCondition)); $rows=$pds->fetchAll();

where I run this I get no results.

If I directly put the $pdoGenderCondition into the PHP PDO statement it works.

I'm guessing you can't put this kind of WHERE clause on the fly into PDO but I believe I've seen it before.

I could use multiple SELECT statements but would rather use one.

Any advise would be greatly appreciated.

thx Adam

Upvotes: 1

Views: 395

Answers (1)

zerkms
zerkms

Reputation: 254896

You cannot do that.

Placeholders can only be used for passing parameters. That's it - no expressions, no database objects names (tables, columns, aliases, stored procedures, ...), just a literal values.

Upvotes: 8

Related Questions