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.

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

报告相同问题?

悬赏问题

  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?
  • ¥15 电磁场的matlab仿真
  • ¥15 mars2d在vue3中的引入问题
  • ¥50 h5唤醒支付宝并跳转至向小荷包转账界面
  • ¥15 算法题:数的划分,用记忆化DFS做WA求调
  • ¥15 chatglm-6b应用到django项目中,模型加载失败
  • ¥15 CreateBitmapFromWicBitmap内存释放问题。
  • ¥30 win c++ socket
  • ¥15 C# datagridview 栏位进度