0

I'm using PDO to develop an application with PostgreSQL. The problem is that the binding functions as PDOStatement::bindValue and PDOStatement::bindParam aren't working at all.

I have the following code:

<?php

    try{

        $db = new PDO("pgsql:dbname=test;host=localhost", "user", "password");

        $all = '*';
        $sql = $db->prepare("SELECT :all FROM schema.table");
        $sql->bindValue(':all', $all);

        var_dump($sql->queryString);
        var_dump($sql->execute());

    }

    catch(PDOException $e){
        print $e->getMessage();

    }

?>

I just cannot understand the reason $sql->queryString's value still is SELECT :all FROM schema.table, as it var_dump()'d here.

PDOStatement::bindParam does exactly the same thing.

Any tips?

EDIT: This query is for debugging purposes only! Please, don't care about the query itself but in the method that isn't binding.

1 Answer 1

3

Prepared statements don't work like that. You can only bind values, not entities.

As far as your statement is concerned, you're executing the query SELECT '*' FROM schema.table, Not, SELECT * FROM schema.table

If you want variable entities (which implies a design flaw about 80% of the time), you will have to resort to string interpolation (or concatenation -- you get the point).

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

8 Comments

Yeah, I know that. I'm using this for debugging purposes. The method should bind it anyway, shouldn't it?
@RodrigoSiqueira It will return the string * repeated the number of times that there are rows matched against the query. So yes, it will bind, but it is not what you think it is.
By the execution of $sql->execute(), my code is querying on the database the string SELECT :all FROM schema.table. If the query were SELECT '*' FROM schema.table or SELECT * FROM schema.table, I'd be pretty much happy because it would be working fine.
@RodrigoSiqueira Hmm, can you set it so that PDO actually throws exceptions so you can see why it's erroring? (Or you can check errorCode or errorInfo)
@Corbin PDO's failure to throw exceptions by default seems to cause so much confusion. Very frustrating that it can't be changed because of BC.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.