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 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动