简体   繁体   中英

Doctrine DBAL prepared query

I'm usigne PHP doctrine DBAL and what I want to do is a get method like this:

function get($attr, $value){
    $conn = DriverManager::getConnection($params, $config);

    $sql = "SELECT * FROM mytable WHERE ? = ?";
    $statement = $conn->executeQuery($sql, array($attrs, $value));
    return $statement->fetchAll();        
}
get("id", 1);

but it doesn't work. I wonder if is possible to obtein parametrization of columns as well as values. Here is the docs I'm using: http://docs.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/data-retrieval-and-manipulation.html#executequery

No, this is not possible. You cannot dynamically bind column name (and this is not doctrine / symfony restriction - it's just how DB works). The way prepare statement works :

Prepared statements basically work like this:

  1. Prepare: An SQL statement template is created and sent to the database. Certain values are left unspecified, called parameters (labeled "?"). Example: INSERT INTO MyGuests VALUES(?, ?, ?)
  2. The database parses, compiles, and performs query optimization on the SQL statement template, and stores the result without executing it
  3. Execute: At a later time, the application binds the values to the parameters, and the database executes the statement. The application may execute the statement as many times as it wants with different values

So you cannot do step 2 without knowing which columns are you going to "use".

ALTERNATIVE SOLUTION: What you want to achieve can be done by preparing sql string first, then parse it (prepared statement) and then bind values

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM