1

Why this one works

    class xyz{
    private $_db;
            function __construct(){

        //database connection 
    }

    function abc($login,$pass,$email){
        $l = "login";
        $check = $this->_db->prepare("SELECT userid FROM users WHERE login = ?");
        $check->execute(array($login));
        $res1 = $check->fetch(PDO::FETCH_NUM);
        return var_dump($res1);
    }
}

And if i change the row selection for login to the variable the code return bool false

    class xyz{
    private $_db;
    function __construct(){

        //database connection 
    }

    function abc($login,$pass,$email){
        $l = "login";
        $check = $this->_db->prepare("SELECT userid FROM users WHERE ? = ?");
        $check->execute(array($l,$login));<<<<<-----THIS $l FAILS TO WORK
        $res1 = $check->fetch(PDO::FETCH_NUM);
        return var_dump($res1);
    }
}

What is the best way to do 3 exactly same queries with different row selections and their values?

  • Why would you want to pass the column name, it will treat is as a string : "SELECT userid FROM users WHERE 'login' = 'whatever'" – ka_lin Mar 01 '13 at 11:23
  • Because I want to check 2 colomns and I've thought maybe it would be better to use same prepeared query for them. Now I see That I have to chose other way to do it. I didn't know that effect of this statment would be "SELECT userid FROM users WHERE 'login' = 'whatever'" – user2062756 Mar 01 '13 at 11:47

2 Answers2

2

You cannot parametrise column names in prepared statements: http://us3.php.net/manual/en/book.pdo.php#69304

More also here: Which tokens can be parameterized in PDO prepared statements?

Community
  • 1
  • 1
Bart Friederichs
  • 33,050
  • 15
  • 95
  • 195
1
  1. Read tag wiki before asking a question.
  2. Among other things there is said "placeholder cannot represent an arbitrary part of the query, but a complete data literal only."
  3. Identifiers have to be formatted and white-listed instead of parameterization. You can see an example in a tag wiki.
  4. the best way to to do 3 exactly same queries with different row selections and their values is to run one query, setting all the conditions into it.
Community
  • 1
  • 1
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
  • Thank you for your answer. I thought about a simmular issues but didn't find anything usefull. I'll recheck this link. – user2062756 Mar 01 '13 at 11:43