Php search engine

hi there. Ive got a search engine that doesn’t work. So far it’s ment to say if there’s any resilts found. However when i’m typing in the keywords it’s saying no results found. could anyone please take a look??



<?php

//get data
$button = $_GET['submit'];
$search = $_GET['search'];

if (!$button)
	echo "You didn't submit a keyword.";
else
{
	if (strlen ($search)<=1)
		echo "Search term too short.";
	else
	{
		echo "You searched for <b>$search</b><hr size='1'>";
	
	//connect to database
	 include('config.php');

	 mysql_select_db("student_bay_co_", $connection);
	
	
			
			
			//explode our search term
			$search_exploded = explode(" ",$search);
			
			foreach($search_exploded as $search_each)
			{
				
			//construct query
				$x++;
				if ($x==1)
					$construct .= "keywords LIKE '%$search_each%'";
				else
					$construct .= " OR keywords LIKE '%$search_each%'";
				
			}
			
		
		
		//echo out construct
		
		$construct = "SELCECT * FROM products1 WHERE $construct";
		$run = mysql_query($construct);
		
		$foundnum = mysql_num_rows($run) ;
		
		if ($foundnum==0)
			echo "No results found.";
		else
		{
			echo "echo $foundnum results found!<p>";
			
		}
		
	
	}
	
}


?>

Here’s a v.quick overview…


<?php
$terms = empty($_GET['search']) ? '' : $_GET['search'] ;

$sql = "SELECT foo FROM table WHERE 1 <> 1";

foreach(explode(' ', $terms) as $term){
  $sql .= sprintf(" OR bar LIKE '%%%s%%'", mysql_real_escape_string($term));
}

$res = mysql_query($sql);

if(0 === mysql_num_rows($res)){
  #no results
}else{
  #some results
}

hi there thanx for the reply. i’m a beginner so i do not fully understand your code. could you explain please :slight_smile:

Sure, I’ve added comments. :wink:


<?php
#check if search terms were sent, if not, set to ''
$terms = empty($_GET['search']) ? '' : $_GET['search'] ;

#create a base sql query that negates all records by default
$sql = "SELECT foo FROM table WHERE 1 <> 1";

#split the searchs terms by space char
foreach(explode(' ', $terms) as $term){
  #find a record where bar is 'like' the $term and add it to the base sql query
  $sql .= sprintf(" OR bar LIKE '%%%s%%'", mysql_real_escape_string($term));
}

#execute query
$res = mysql_query($sql);

if(0 === mysql_num_rows($res)){
  #no results
}else{
  #some results
}

If you’re unsure of any of the functions used, see the manual; it’s much better than me at explaining them. :stuck_out_tongue: