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?

2
  • Why would you want to pass the column name, it will treat is as a string : "SELECT userid FROM users WHERE 'login' = 'whatever'" Commented Mar 1, 2013 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'" Commented Mar 1, 2013 at 11:47

2 Answers 2

2

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

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

Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

Thank you for your answer. I thought about a simmular issues but didn't find anything usefull. I'll recheck this link.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.