Simple Site Search With PHP and MySQL

Go To StackoverFlow.com

0

I'm looking for a script for a simple search engine that involves only 2 or three variables.

For my site I have a database table named search and 3 fields: url, title, and content.

Can someone please help me build a simple processing script for this please? I would only like the title and the content to be searched.

2012-04-05 17:07
by 4WebDev


0

You could create a query like:

$prepared = $db->prepare('SELECT * FROM search WHERE title LIKE "%:search_value%" OR content LIKE "%:search_value%"');
$prepared->execute(array(':search_value' => $search_value));
$rows = $prepared->fetchAll();

Where $db is a PDO object.

2012-04-05 17:10
by Captain Insaneo
Thanks just what I was looking for : - 4WebDev 2012-04-05 17:12
bad practice -- vulnerable to SQL injections. Always use a sql library that can prepare your queries. If you use adodb you get cross-db compatibility for free - j13r 2012-04-05 17:13
@j13r - Would a simple mysqlrealescape_string() work or another built in PHP funciton - 4WebDev 2012-04-05 17:14
@j13r Alright, I was assuming the $search_value would be sanitized. I'll add it in to be explicitly clear - Captain Insaneo 2012-04-05 17:14
sweet thanks for the help guys - 4WebDev 2012-04-05 17:15
Consider looking into PDO for SQL tasks like this. Using placeholders can help prevent SQL injections. It's also useful for many other database related tasks - opes 2012-04-05 17:16
I wouldn't assume that; there are various forms of SQL injections. See here: http://stackoverflow.com/questions/5690795/am-i-safe-using-just-mysql-real-escape-string-to-defend-sql-injections#5690804 There is also an example of how to use prepared statements with MySQLi here: http://www.ultramegatech.com/2009/07/using-mysql-prepared-statements-in-php - j13r 2012-04-05 17:18
Updated the answer to use prepared statements - Captain Insaneo 2012-04-05 17:30
Hey everyone... This might be pushing it a bit but in my while loop when I display my results I was wondering if their was a way to just grab the 100 characters around the search_value. Again if it's too much then don't bother - 4WebDev 2012-04-05 17:45
Ads