-2

I have created search box using php and mysql, for that, I have created index.php and search.php files.

And i have created database named as search.

Here is my code:

Index.php:

<html>
<head>
<title>Title of your search engine</title>
</head>
<body>
<form action='search.php' method='GET'>
<center>
<h1>My Search Engine</h1>
<input type='text' size='90' name='search'></br></br>
<input type='submit' name='submit' value='Search source code' ></br></br></br>
</center>
</form>
</body>
</html>

search.php:

<?php
$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'></br>";
mysql_connect("localhost","root","");
mysql_select_db("search");
 $search_exploded = explode (" ", $search);
 foreach($search_exploded as $search_each)
{
$x++;
if($x==1)
$construct .="keywords LIKE '%$search_each%'";
else
$construct .="AND keywords LIKE '%$search_each%'";
 }
 $construct ="SELECT * FROM searchengine WHERE $construct";
$run = mysql_query($construct);
 $foundnum = mysql_num_rows($run);
 if ($foundnum==0)
echo "Sorry, there are no matching result for <b>$search</b>.</br></br>1.
Try more general words. for example: If you want to search 'how to create a website'
then use general keyword like 'create' 'website'</br>2. Try different words with similar
 meaning</br>3. Please check your spelling";
else
{
echo "$foundnum results found !<p>";
 while($runrows = mysql_fetch_assoc($run))
{
$title = $runrows ['title'];
$desc = $runrows ['description'];
$url = $runrows ['url'];

echo "
<a href='$url'><b>$title</b></a><br>
$desc<br>
<a href='$url'>$url</a><p>
";
 }
}
 }
}
 ?>

When will run this code, it shows following errors,

Notice: Undefined variable: x in C:\xampp\htdocs\selva\search\search.php on line 21

Notice: Undefined variable: construct in C:\xampp\htdocs\selva\search\search.php on line 23

Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\selva\search\search.php on line 32

can anyone help to fix this, Thanks in advance.

deepika
  • 61
  • 11

1 Answers1

0

Try, Define

 $x = 0; 
 $construct = ''; 

before the foreach loop.

mysql_query() returns false if the query failed. That's why mysql_num_rows() complains about receiving a boolean value.

Amal
  • 546
  • 6
  • 19