I’m trying to upgrade a Coldfusion8/MySQL site. The site has a complex search which, (among other criteria) takes text strings and searches these in a keyword table.
I don’t want to do a FULLTEXT search, because the full query has a lot of extra conditions. What I’m looking for is to make the following more “dynamic”, that is not limit myself to xy words and thereby maybe shortening this a bit (the full search has plenty of blocks like this).
So, say I have a search string like
I'm looking for something
I’m currently doing this:
<!--- params --->
<cfparam name="s01" default="">
<cfparam name="s02" default="">
<cfparam name="s03" default="">
<cfparam name="s04" default="">
<cfparam name="s05" default="">
<!--- get length of search string --->
<cfset howManyWords = ListLen(textSearch," ")>
<!--- assign words to params --->
<cfif howManyWords gt 0><cfset s01 = trim(ListGetAt(textSearch, 1," "))></cfif>
<cfif howManyWords gt 1><cfset s02 = trim(ListGetAt(textSearch, 2," "))></cfif>
<cfif howManyWords gt 2><cfset s03 = trim(ListGetAt(textSearch, 3," "))></cfif>
<cfif howManyWords gt 3><cfset s04 = trim(ListGetAt(textSearch, 4," "))></cfif>
<cfif howManyWords gt 4><cfset s05 = trim(ListGetAt(textSearch, 5," "))></cfif>
In my search query, I’m matching the search strings to three database fields:
...
<cfif textSearch neq "">
<cfif s01 neq "">AND (a.textSearch LIKE "%#s01#%" OR a.textSearch_xl LIKE "%#s01#%" OR a.ean = "#s01#")</cfif>
<cfif s02 neq "">AND (a.textSearch LIKE "%#s02#%" OR a.textSearch_xl LIKE "%#s02#%" OR a.ean = "#s02#")</cfif>
<cfif s03 neq "">AND (a.textSearch LIKE "%#s03#%" OR a.textSearch_xl LIKE "%#s03#%" OR a.ean = "#s03#")</cfif>
<cfif s04 neq "">AND (a.textSearch LIKE "%#s04#%" OR a.textSearch_xl LIKE "%#s04#%" OR a.ean = "#s04#")</cfif>
<cfif s05 neq "">AND (a.textSearch LIKE "%#s05#%" OR a.textSearch_xl LIKE "%#s05#%" OR a.ean = "#s05#")</cfif>
</cfif>
...
Question:
Is there a way to make this more dynamic, for example with a loop, so I’m not stuck with 5 words? How would I preset the param values in this case?
Thanks for help!
You can just explode the search term by looping over it as a list within the query, you should also be using query parameters to prevent SQL injection attacks.