using prepared mysqli statements to bind parameters into the SELECT section of a query

橙三吉。 提交于 2021-01-28 00:39:11

问题


I am building a web app that imports data from data feeds in php/mysql. I import the data into a buffer/temp holding table. As each data format is different I choose the column to select based on the particular source.

I am having trouble getting this query to work in this context :

$stmt = $this->dbObj->prepare("SELECT mk.PK_phone_maker, b.?, b.phoneDescription
            b.thumbPic,
        FROM buffer_table b left join mobile_phone pm on b.? = pm.phoneModel
            LEFT JOIN phone_maker mk on mk.CompanyName = b.?
        WHERE pm.phoneModel is null
        group by b.?");
$stmt->bind_param('ssss',$phoneModelField, $phoneModelField, $phnMakerField,$phoneModelField);
$stmt->execute();

I recieve the error msg:

Fatal error: Call to a member function bind_param() on a non-object

This refers to the line:

 $stmt->bind_param('ssss',$phoneModelField, $phoneModelField, 

And I assume this is because the "prepare" on my sql hasnt worked as $stmt is not an object

As such it appears to me that you can not bind parameters to select columns and join fields, you can only bind to the where clause. Am I right in this assertion or am I missing something?


回答1:


Prepared statements only allow you to bind values, other constructs (such as fields, tables or functions, let alone whole bits of SQL) are not allowed.




回答2:


@Victor Nicollet is correct -- you can use a query parameter only in a context where you could have used a literal value.

If you need to make other parts of your query variable (e.g. column name, table name, SQL keywords, or whole SQL expressions), you need to build a dynamic SQL query as a string, and interpolate PHP variables or expressions into the string. Be sure to do this carefully to avoid SQL injection vulnerabilities.

The other WTF in your code is that you didn't check that the prepare() function returned an object of type mysqli_stmt. In this case, because you used query parameters in an invalid way, prepare() returned false to indicate a syntax error. Of course false is not an object; it doesn't have a bind_param() method. That's why you got the error you did.



来源:https://stackoverflow.com/questions/2138825/using-prepared-mysqli-statements-to-bind-parameters-into-the-select-section-of-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!