Skip to content Skip to sidebar Skip to footer

Mysqli Parameter Binding Issue

I need an extra set of eyes on this one. Any help will be greatly appreciated. This is a very simple search query, but for whatever reason I cannot find the bug. Well, I know where

Solution 1:

$suquery=$dbCon->prepare("select * from Table where ? LIKE ?");

Will not work as expected. It will get translated as:

SELECT*fromtableWHERE'columnName'LIKE'%a%'

which returns all rows because 'columnName' contains an 'a'. 'columnName' is a string, not an actual column name.

Your second attempt is correct, except you have an extra quotes in the term. When using parameters, you don't need any quotes. The solution is:

$term = "%".$_POST['searchTerm']."%";
$suquery=$dbCon->prepare("select * from Table where columnName LIKE ?");
$suquery->bind_param('s', $term);
$suquery->execute();

Solution 2:

EDIT: Original Answer was based on false assumption (assumed PDO instead of mysqli). Changed answer accordingly.

It looks like you are not allowed to use parameter substitution for column names. From the mysqli::prepare documentation:

Note: The markers are legal only in certain places in SQL statements. For example, they are allowed in the VALUES() list of an INSERT statement (to specify column values for a row), or in a comparison with a column in a WHERE clause to specify a comparison value. However, they are not allowed for identifiers (such as table or column names), in the select list that names the columns to be returned by a SELECT statement, or ...

You might want to verify this by hardcoding the column/field name in the query and just replacing the comparison value via parameter...

Post a Comment for "Mysqli Parameter Binding Issue"