duan20145 2015-08-17 10:50
浏览 41
已采纳

Doctrine DBAL准备了查询

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

  • 写回答

1条回答 默认 最新

  • dtziv24262 2015-08-17 10:59
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?