简体   繁体   中英

Combine LIKE and IN in PHP MySQLi prepared statement

Trying to build a searchpage for an equipment database, and I have a prepared statement which takes an equipment 'tag' (always required) and searches a keyword in six different data fields where the 'tag' matches user input.

The problem is that no results are found if the keyword is IN one of these possibly long fields, so many intended results are missing.

In regular SQL I'd just to a table join and add a LIKE query to an IN query; but with mysqli I'm using a prepared statement with the ? placeholder and not sure what can be done about using this mark more than once for each variable.

The statement I have is this:

if (!($stmt = $conn->prepare("SELECT * FROM equipment 
    WHERE EQUIP_CND LIKE ? 
    AND (EQUIP_TYP LIKE ? OR ((EQUIP_SER LIKE ? OR EQUIP_PNO LIKE ?) 
        OR (EQUIP_LOC LIKE ? OR EQUIP_CMT LIKE ?)));"))) {
echo "Prepare failed: (" . $conn->errno . ") " . $conn->error;
}

And I want to just replace LIKE with LIKE IN . How to achieve this?

The like requires wildcards to have loose matching.

eg

select * from table where a like 'b'

is the same as:

select * from table where a = 'b'

so a record of b would be found but abc would not.

From the manual :

With LIKE you can use the following two wildcard characters in the pattern:

% matches any number of characters, even zero characters.

_ matches exactly one character.

So to find abc you'd use:

select * from table where a like '%b%'

For prepared statements the wildcards get appended to the variable, or in the binding, NOT in the query itself. Example 6 on the PDO manual page shows this. http://php.net/manual/en/pdo.prepared-statements.php#example-991 (after the comment // placeholder must be used in the place of the whole value )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM