-1

This is my search engine php code. I have three fields in database: Title, Description and Url. But it will only display a search query that matches the Title. How to create a search query to match with Title, Description and Url?

<?php

ini_set('display_errors',0); // turn off php notice  & errors


$button = $_GET ['submit'];
$search = $_GET ['search'];

if(strlen($search)<=1)
echo "Search term too short";
else{
echo "You searched for <b>$search</b> <hr size='1'></br>";
mysql_connect("localhost","woogle","woogle");
mysql_select_db("search");                  

$search_exploded = explode (" ", $search);

foreach($search_exploded as $search_each)
{
$x++;
if($x==1)
$construct .="title LIKE '%$search_each%'";
else
$construct .="AND title LIKE '%$search_each%'";
}


$constructs ="SELECT * FROM searchengine WHERE $construct";

$run = mysql_query($constructs);

$foundnum = mysql_num_rows($run);

if ($foundnum==0)
echo "Sorry, there are no matching result for <b>$search</b>";
else
{
echo "$foundnum results found !<p>";
}
Joel
  • 4,732
  • 9
  • 39
  • 54
  • 5
    Wow, is it just me or does that seem ripe for being exploited? – j08691 Feb 04 '14 at 21:00
  • One thing is that it doesn't look like you query searches the `description` or `url`. Right now I only see code that searches the `title` – Gohn67 Feb 04 '14 at 21:01
  • 1
    Woogle....that's fun xD – Hackerman Feb 04 '14 at 21:02
  • Unfortunately I'm going to have to agree with the others that this code needs to be written if you plan to use this in a production setting. Even for learning purposes, it may be best to take the time to learn more secure approaches. – Gohn67 Feb 04 '14 at 21:03
  • 1
    If you don't want to use parameters, you should at least use http://us3.php.net/mysql_escape_string – Tim Feb 04 '14 at 21:08
  • 1
    You should read on [how to prevent SQL injections with PHP](http://stackoverflow.com/q/60174/53114) as your script is vulnerable to it. – Gumbo Feb 04 '14 at 21:13

2 Answers2

1

Try this:

foreach($search_exploded as $search_each)
{
    $x++;
    $search_each_e = mysql_real_escape_string($search_each);    // To help prevent SQL injection
    if($x==1)
        $construct .="(title LIKE '%$search_each_e%' OR description LIKE '%$search_each_e%' OR url LIKE '%$search_each_e%')";
    else
        $construct .="AND (title LIKE '%$search_each_e%' OR description LIKE '%$search_each_e%' OR url LIKE '%$search_each_e%')";
}

You can escape the strings to prevent SQL injection. However, I think that using prepared statements is a more robust approach.

Community
  • 1
  • 1
Guillermo Gutiérrez
  • 17,273
  • 17
  • 89
  • 116
0

try this :

 $construct = " 1 " 

 foreach($search_exploded as $search_each)
 {
   $construct .=" AND (title LIKE '%$search_each%' OR description LIKE '%$search_each%' OR url LIKE '%$search_each%')";
 }
Jérôme Teisseire
  • 1,518
  • 1
  • 16
  • 26