简体   繁体   中英

How can I use a php array in a mysql search query?

I was going to use the scuttle solution on: http://www.pui.ch/phred/archives/2005/04/tags-database-schemas.html for handling searches on my website. I was wondering how I could take the search input from a user and turn it into a single query.

For instance, let's say a user inputted 'blue dogs' in their search query... How could I dynamically update the query to include ('blue', 'dogs') in union and intersection queries?

The methods posted here are correct, just one little security addition: Don't forget to escape the user inputted data, otherwise you're just one step away from SQL injections. Or avoid the query and use prepared statements instead: PHPManual Prepared Statements

for example your user input is "blue dogs", then on the page

$searchstring = "blue dogs"; // or fetch the input
$arr = explode(" ",$searchstring); //this is explode the text by every "space" character

you have the user inputed string in array $arr now, now use it in query like you usually do

You can do like:

$search_string = implode(',', $search_array);

Now in your query you can use the IN clause:

$query = "select * from table where field IN ('".$search_string."')";

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