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

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

报告相同问题?

悬赏问题

  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM