Searching articles for hand-picked keywords

Creating the SQL statement

The first task is to turn the search expression into a SQL statement.

// get data from form
var sSearch = '' + Request.Form ( 'SearchText' );

if ( sSearch.length )
{
  // remove all reserved characters
  sSearch = sSearch.replace ( /['"%]/g, '' );

  // split into array, then reform with AND
  var sArray = sSearch.split ( ' ' );
  var sSQLSearch = '';

  for ( var i=0; i<sArray.length; i++ )
  {
     if ( i )
        sSQLSearch += ' AND ';

     sSQLSearch += 'Keywords LIKE \'% ' + sArray [ i ] + '%\'';
  }

Starting from the top, we ask the form for the SearchText value and make sure there was something entered by testing that the length property is non-zero. Next, I use the replace method with a regular expression that removes any ' " % characters in the search expression to make it "SQL safe". I then use the split method to create an array of items using a space as the separator.

Lastly I loop through the array items making up the sSQLSearch string. I separate multiple words with AND, and wrap the expressions you typed with the wildcard % character. Note that I include a space after the first %, so you'll only find keywords that start with your expressions. (I prefix every word in the Keywords field with a space, even the first one)

You might also like...

Comments

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Beware of bugs in the above code; I have only proved it correct, not tried it.” - Donald Knuth