douzhuang2016 2011-08-17 08:46
浏览 73
已采纳

占位符对于SQLite表在PHP中

I have a query I would like to use that I would like to be reused for other select queries.
Is it possible to have a select query like this:

SELECT * FROM ? WHERE id = ?;

And then bind the values like this:

$stmt->bindValue(1, $table, PDO::PARAM_STR);  
$stmt->bindValue(2, $id, PDO::PARAM_INT);

The problem is when I do this I get this $database->errorInfo() from a PDOException

HY000 1 near "?" syntax error.

I have tried taking out the table placeholder and it does work. Is it possible to do it my way or do I need to have separate functions?

  • 写回答

1条回答 默认 最新

  • duanmeng9336 2011-08-17 09:19
    关注

    Short answer: NO.


    Long answer:

    Refer to the PDO::prepare manual. There is a statement: This must be a valid SQL statement for the target database server. This means that your DB backend have to support prepared statement syntax that you use.

    As far as I know, neither mysql, nor any other DB does not allow binding variables to occur in FROM clause. The reason for that lays deep in the concept of prepared statement. Prepared statement is being prepared inside the DB when you are calling prepare. This means that DB planner builds a plan for the query, so it can be executed multiple times with different parameters without building it again and again. To build a plan, planner needs to know affected tables, functions called, opportunities to use different fetch and join strategies (index scans/nested loops/etc.) and so on.

    So, you cant 'bind' table name into prepared statement at the moment you want it to run, because DB needs table names at the moment when you prepare the statement. That's why you receive that message: DB requires all table names to be present in the preparing query.

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

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?