“Unknown column in 'field list'” when prepared statement's placeholder is in subquery

后端 未结 1 580
慢半拍i
慢半拍i 2020-12-21 05:53

I\'m using PHP 5.5.9 and MySQL 5.5.44 with mysqlnd 5.0.11-dev on Ubuntu 14.04 LTS. The following statement fails to prepare:

$db->prepare(\"SELECT nr.x FR         


        
相关标签:
1条回答
  • 2020-12-21 06:37

    Your latest edit made the question very clear, so I'll attempt an answer: the cause of this difference is the placeholder.

    As documented here, placeholders can only be used in certain places in the query. In particular:

    Parameter markers can be used only where data values should appear, not for SQL keywords, identifiers, and so forth.

    Now you might have noticed that SELECT ? as x prepares fine, but not SELECT nr.x FROM (SELECT ? AS x) AS nr. Why is that? Well this is best explained by an anonymous author on PHP's doc, so let me copy/paste:

    There is a common misconception about how the placeholders in prepared statements work: they are not simply substituted in as (escaped) strings, and the resulting SQL executed. Instead, a DBMS asked to "prepare" a statement comes up with a complete query plan for how it would execute that query, including which tables and indexes it would use, which will be the same regardless of how you fill in the placeholders.

    So simply put: because you are using a placeholder in a subquery in the FROM clause, MySQL cannot calculate the execution plan of the query.

    In other words, since your query will always change, there is not "template" that can be prepared for it.

    Therefore if you really want to use this query, you need to use a normal (non-prepared) query, or turn back on PDO's emulated prepared statements.

    That being said, please, do consider the various alternatives offered in the comments section. There are much better solutions for what you are trying to achieve.

    0 讨论(0)
提交回复
热议问题