Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Search engine script

Status
Not open for further replies.

rogerzebra

Technical User
May 19, 2004
216
SE
Hi again everyone..

I found this script on a search engine and I tried to implement it on my intranet but it doesn't work, so I would appreciate if someone could take a look at it and help me to figure it out of what's wrong with it. It givs me a error on line 71.
I thought it would be good for me to put up the whole script in case of there is any other faults. So thanks in advance for any input and I would be most grateful if someone could explain parts of the code I don't get. (marked in red...)..I actually thought is was more than one script??..I know it's possible to use several php tags in one script bot beneth the </html> end tag?



<?php

$submit = $_POST["submit"];
$keywords = $_POST["keywords"];

if(isset($submit) || isset($keywords))

{

doSearch($keywords);

}

else

{

getKeywords();

}

function getKeywords()

{

}

function doSearch($search_keywords)

{

}


function getKeywords()

{


?>

<html>
<head><title> Enter Search Keywords </title></head>

<body bgcolor="#FFFFFF">

<form name="frmKW" action="searchdocs.php" method="post">
<h1>Keyword Search</h1> Enter keywords to search on:
<input type="text" name="keywords" maxlength="100"><br><br>
<input type="submit" name="submit" value="Search">

</form>
</body>
</html>


<?php

}

function doSearch($search_keywords)

{
$arrWords = explode(" ", $search_keywords);
if(sizeof($arrWords) == 0 || $search_keywords == "")
{

echo "You didn't enter any keywords<br>";
echo "<a href='searchdocs.php'>Go Back</a>";

}

else


{

// Connect to the database
$dbhost = 'localhost';
$dbusername = 'root';
$dbpasswd = 'matrix';
$database_name = 'intranet';

$s = @mysql_connect($dbhost, $dbusername, $dbpasswd)
or die("Couldn't connect to database server");

@mysql_select_db($database_name, $s)
or die("Couldn't connect to database");


for($i = 0; $i < sizeof($arrWords); $i++)
{
$query = "select articleIds from searchWords where word = '{$arrWords[$i]}'"; [color]

$result = mysql_query($query);


if(mysql_num_rows($result) > 0)

{

// Get the id's of the articles

$row = mysql_fetch_array($result);

$arrIds = explode(",", $row[0]);

$arrWhere = implode(" OR articleId = ", $arrIds);

$aQuery = "select articleId, title, left(content, 100) as summary
from articles where articleId = " . $arrWhere;

$aResult = mysql_query($aQuery);
$count = 0;

//Each article returned from the select query is added to an associative array called $articles:

$articles = array();

if(mysql_num_rows($aResult) > 0)

{

while($aRow = mysql_fetch_array($aResult))

{

$articles[$count] = array ("articleId" => $aRow "articleId"],
"title" => $aRow["title"], "summary" => $aRow["summary"]);

$count++;

}

}

//At this point, the $articles associative array will contain all of the articles returned from the search.

if(isset($articles))

{

$articles = array_unique($articles);

echo "<h1>" . sizeof($articles);

echo (sizeof($articles) == 1 ? " article" : " articles");

echo " found:</h1>";

foreach($articles as $a => $value)

{

?>

<a href="article.php?articleId=<?php echo $articles[$a]["articleId"]; ?>">
<b><u><?php echo $articles[$a]["title"]; ?></u></b>
</a>

<br><?php echo $articles[$a]["summary"] . "..."; ?><br>

<a href="article.php?articleId=<?php echo $articles[$a]; ?>">
echo $articles[$a]["articleId"]; ?>
</a>

<br><br>

<?php

}

}

else

{

echo "No results found for '$search_keywords'<br>";

echo "<a href='searchdocs.php'>Go Back</a>";

}

}
}
}

?>

It refer to a link article.php in this script but in the tutorial they never mentioned to make a article.php page or am I reading this wrong?...or am I supposed to change that to searchdocs.php??
This is the original script and I haven't done any changes to it.
I'm greatful for any help on this or open to suggestions to another script regarding search engines for pulling data from your database.
/rz
 
Use code tags, without indentation reading it is a pain. Also, possibly include a link to a .txt file with the source of your php script, as my line 71 will probably differ to your line 71 using cut and paste.
 
Hi kwijibo,
Thanks for taking your time, I really appreciate it and now it's hopfully much easier to read(sorry for that).
This is my error message:
Fatal error: Cannot redeclare getkeywords() (previously declared in C:\apachefriends\xampp\htdocs\intranet\searchdocs.php:26) in C:\apachefriends\xampp\htdocs\intranet\searchdocs.php on line 71


Question it's possible to use php tags beneth the </html> end tag?


Code:
<?php

          $submit = $_POST["submit"]; 
     $keywords = $_POST["keywords"];

     
      if(isset($submit) || isset($keywords)) 

           { 
           doSearch($keywords); 
           } 
       
     
      else 

        [COLOR=red]{ 
        getKeywords(); 
        }
          
          function getKeywords() 
          {

            }
            function doSearch($search_keywords) 
            {

            }
             function getKeywords() 
            { 
[/color]

 ?>

<html>
<head><title> Enter Search Keywords </title></head>

  <body bgcolor="#FFFFFF">
    
      <form name="frmKW" action="searchdocs.php"    method="post">

         <h1>Keyword Search</h1> 
            Enter keywords to search on: 

         <input type="text" name="keywords"    maxlength="100"><br><br>

         <input type="submit" name="submit" value="Search">

       </form>
    </body>
 [COLOR=red] </html>[/color]


<?php 

         }
          function doSearch($search_keywords)  
         { 
  [COLOR=red]
        $arrWords = explode(" ", $search_keywords);
    if(sizeof($arrWords) == 0 || $search_keywords == "") { 
[/color]

echo "You didn't enter any keywords<br>"; 
  echo "<a href='searchdocs.php'>Go Back</a>"; 

        } 

        else

        {

// Connect to the database 
$dbhost = 'localhost'; 
$dbusername = 'root'; 
$dbpasswd = 'matrix'; 
$database_name = 'intranet';

      
  $s = @mysql_connect($dbhost, $dbusername, $dbpasswd) 
       or die("Couldn't connect to database server");

           @mysql_select_db($database_name, $s) 
             or die("Couldn't connect to database");


[COLOR=red]
       for($i = 0; $i < sizeof($arrWords); $i++) 
       { 
         $query = "select articleIds from searchWords where  word = '{$arrWords[$i]}'"; [color]

    
        
       $result = mysql_query($query);
          if(mysql_num_rows($result) > 0) 

        { 

   

 // Get the id's of the articles 

       $row = mysql_fetch_array($result); 
         $arrIds = explode(",", $row[0]); 

  
        $arrWhere = implode(" OR articleId = ", $arrIds);


      $aQuery = "select articleId, title, left(content,  100) as summary from articles where articleId = " . $arrWhere;

    
       $aResult = mysql_query($aQuery); 
            $count = 0;



//Each article returned from the select query is added to an associative array called $articles:

      $articles = array();

          
       if(mysql_num_rows($aResult) > 0) 
          { 
            while($aRow = mysql_fetch_array($aResult)) 
          { 



         $articles[$count] = array ("articleId" =>   $aRow "articleId"], "title" => $aRow["title"], "summary" => $aRow["summary"]); 


[COLOR=red]
    $count++; 
[color]
       } 

       }

//At this point, the $articles associative array will contain all of the articles returned from the search.


     if(isset($articles)) 

      { 

      $articles = array_unique($articles); 

          
         echo "<h1>" . sizeof($articles); 

          
         echo (sizeof($articles) == 1 ? " article" : " articles"); 
        

         echo " found:</h1>"; 

           foreach($articles as $a => $value) 

           { 

?>

<a href="[COLOR=red]article.php[/color]?articleId=<?php echo $articles[$a]["articleId"]; ?>">

 
<b><u><?php echo $articles[$a]["title"]; ?></u></b></a>

<br><?php echo $articles[$a]["summary"] . "..."; ?><br>



<a href="[COLOR=red]article.php[/color]?articleId=<?php echo $articles[$a]; ?>"> 

[URL unfurl="true"]http://localhost/article.php?articleId=<?php[/URL] echo $articles[$a]["articleId"]; ?> 
</a>

<br><br> 

<?php 

      } 
      }

      else 

      { 

       echo "No results found for '$search_keywords'<br>"; 
    echo "<a href='searchdocs.php'>Go Back</a>"; 

      } 

      } 
      } 
      }

?>

It refer to a link article.php in this script but in the tutorial they never mentioned to make a article.php page or am I reading this wrong?...or am I supposed to change that to searchdocs.php??
This is the original script and I haven't done any changes to it.
I'm greatful for any help on this or open to suggestions to another script regarding search engines for pulling data from your database.
/rz
 
Hmm... not sure about the multiple <?php - ?> pairs, as I'm still learning this particular language.

I would, however, use the echo statement to display the html. That way you wouldn't have the issue of the multiple php sections.

Something like this would suffice:

Code:
echo """
<html>
<head><title> Enter Search Keywords </title></head>

... rest of html goes here ...

</html>
""";

I don't have time to look at the whole thing now (at work :) ), but I will look quickly at the fisrt section. Try to indent your code (good practise), it helps you see where you miss things, particularly braces. I have adjusted your first section of code. I find it easier to read like this:

Code:
<?php

$submit = $_POST["submit"];
$keywords = $_POST["keywords"];

if(isset($submit) || isset($keywords))
{
   doSearch($keywords);
}
else
{
   getKeywords();
}

function getKeywords()
{
}

function doSearch($search_keywords)
{
}

function getKeywords()
{
?>

The first line in red:
Code:
   getKeywords();

This is a function call. The program looks for the function getKeywords() and executes all the code within the braces.

The second part in red:
Code:
function getKeywords()
{
}

This is the implementation of your getKeywords function. In other words, when you write the previously explained getKeywords(); line in your code, your program will execute any instructions between the opening { and closing }. The same applies for the doSearch() function, with one exception. This function (below), takes a variable $search_keywords as a parameter.
Code:
function doSearch($search_keywords)
{
}

Also, you will notice these function are empty. You need to put some code in between the {} to actually have the script do something. Furthermore, there seems to be a brace left off at the bottom of the first section, which is also the source of your first error:
Code:
function getKeywords()
{

?>

We have already declared a function higher up in the program with the name getKeywords(). We can't have two the same name (in a scripting language anyway), or the program won't know which one to call. Try removing the second definition and the start brace and go from there.

Oh, and excuse any syntax errors / typos I may have made above.
 
And yes, you can have as many blocks of
<?php
?>

as you like in your page. You cannot embed them within each other, but you can go back and forth... it's called context switching if you want to read up on it.

I personally would recommend against it however as it tends to hurt the performance of your script.
 

There you go. I've learnt something too :)
 
kwijibo,

Thanks again for your input. the script actually works except for the href link. What does this code do? The link doesn't work unless I actually have a link to a page article.php right?

Code:
<a href="article.php?articleId=<?php echo $articles[$a]["articleId"]; ?>">

My intension is to register all articles and searchwords thru a form page. Then be able to search in the database and when the result shown get a link to the actual information and not the article.php link.

Make the hole search engine dynamic which it's not with this solution. For instance now I have to match article id in the articles table with the article id in the searchword table. Which mean that I manually need to check what id the article get when registered and put that id value in the searchword tables article id. Is there any other solution or scripts who can do these things?

I'm not able yet to buildt something like that, so all suggestions and inputs are very valuable for me so thanks again and I'll be happy to here from anyone with suggeestions to built this more dynamic and perhaps a function to locate other file formats aswell.

/rz
 
You are correct that the code
Code:
<a href="article.php?articleId=<?php echo $articles[$a]["articleId"]; ?>">
is a link to a file article.php. If that file does not exist, the link will not work.
 
Thanks for the explanation aardvark92.

I felt that I needed to further explain want I want my script to do, so here it goes. The code a href link beneth does what I actually wanted after I've now manually changed it in the script it find my word document in my database.
But it is a static value, so now I'm looking for a function to change the value in the a href link script part, based on my search automaticly register a new link adress and the returned search result shows me the link to the document in my database.

Hmmm hope my explanation is clear enough for you guys to understand.

Code:
<a href="Magellan Intranet is a great database.doc?articleId=<?php echo $articles[$a]; ?>"> 
	[URL unfurl="true"]http://localhost/intranet/Magellan[/URL] Intranet is a great database.doc?articleId=<?php echo $articles[$a]["articleId"]; ?> 
</a>

any ideas?
 
Hmmm... Not sure I understand fully, but I will try to help.

Assuming your database query returns some sort of value corresponding to the file name, outputting the link is fairly simple. If the database returned a variable called $filename for instance, the code to display the link would be:

Code:
<a href="<?php echo $filename; ?>?articleId=<?php echo $articles[$a]; ?>">[URL unfurl="true"]http://localhost/intranet/<?php[/URL] echo $filename; ?>?articleId=<?php echo $articles[$a]["articleId"]; ?>
</a>

Or more simply, remembering to use the breakout character to actually print the required "'s (ie. \"):

Code:
echo "<a href=\"".$filename."?articleId=".$articles[$a]."\">
[URL unfurl="true"]http://localhost/intranet/".$filename."?articleId=[/URL]
".$articles[$a]["articleId"]."</a>";

Hope this helps.
 
Hey kwijibo,
I'm sorry I don't get it..

Assuming your database query returns some sort of value corresponding to the file name.. I've tried on my own but I don't get it..headache,..so please explain. I'm still a newbie.
/rz
 
kwijibo,

In order for me to know what value the query returns, I need to echo the query, but it doesn't allow me to?
am I right?
 
Echoing a variable will, yes, show you the value.

You shouldn't need to 'know' the value, just the variable name the value is stored in. Then, replace the $filename variable in my above code with the variable name that contains the value.

This is getting into a realm I am unfamiliar with. but try something like this with my above code:

Code:
$filename = mysql_query(...);
 
kwijibo
I'm sorry have been a bit slow the last weeks...newborn baby..no sleep..sorry so obvious..you couldn't explain it more clear than you did and thanks so much. This is what i got this time:

1 article found:
TEST_MONDAY
born...
id #3 articleId=3
but when I clic the link it takes me to this url??

Any clue why this link to nowhere comes up??

Thanks for your patience, I'm still learning and I hope soon enough to be an access to anyone else.
/rz
 
The link is displaying in response to this code:

Code:
echo "<a href=\"".$filename."?articleId=".$articles[$a]."\">
[URL unfurl="true"]http://localhost/intranet/".$filename."?articleId=[/URL]
".$articles[$a]["articleId"]."</a>";

It might help if Itry to explain whats going on in the link.
Take this link:

The '?' after the resource.php indicates to the script that it should expect data to be passed in. The '&' symbol tells the script there is more data to be passed in (kind of like a seperator, I guess). In this case we are passing in a number 3 and a string 'Kwijibo', which will be store in a variable $ID and $name respectively. Usually in our resource.php there will be a few lines similar to this:

Code:
if(!$ID)
{
   echo "ERROR: enter valid ID";
   die();   // exit due to error
}
if(!$name)
{
   echo "ERROR: enter valud name";
   die();   // exit due to error
}

In your main code, you will need to generate a link in this format, in order for the user to be able to click on it and have it display resource.php properly.

Now, to your question. What is happening is your script appears to be inserting spaces instead of the '?' and '=' characters. Try inserting the break-out character '\' before these in your code. This character '\' tells the script that the following character is a special character, and not text. For example, take the string: My name "Kwijibo" is part of a string.

To echo this to the screen, you would need to do this:

Code:
echo "My name \"Kwijibo\" is part of a string."

So, try this as your link code:

Code:
echo "<a href=\"".$filename."?articleId=".$articles[$a]."\">
[URL unfurl="true"]http://localhost/intranet/".$filename."\?articleId\=[/URL]
".$articles[$a]["articleId"]."</a>";

Notice the \? and the \=. Also, for future reference, to insert a '\' as text, use \\.

I'm not sure if the '\' will work, if not I might have to look at the code in a bit more detail.

I hope this helps, sorry about the length :)
 
kwijibo,
No need to be sorry I appreciate your effort and I really appreciate your explainations. I'm not so sure about the placement for the other two backslashes though after a href=\"" and the "\" but believe me I've tried all different placements for them. The code with added backslashes changed the result to this:

Forbidden
You don't have permission to access /"".$filename." on this server.

1 article found:
TEST_MONDAY
born...
id #3 articleId=3

articleId=3 is the correct ID in the database for document test_monday but Resource id #3..I have no idea what that referrs to??

and when I clic the link above it takes me to a blank page and it shows me this url??

Code:
echo "<a href=[B]\[/B]"".$filename."?articleId=".$articles[$a]."[B]\[/B]">
[URL unfurl="true"]http://localhost/intranet/".$filename."\?articleId\=[/URL]
".$articles[$a]["articleId"]."</a>";

If i delete the bolded backslashes in the code above the link takes me to index.php in the folder intranet and not the word document test_monday.doc ....,so I guess it finds it's way to the folder at least but why open the link index.php?

Here is the whole code again
Code:
<?php

$submit = $_POST["submit"]; 
$keywords = $_POST["keywords"];

if(isset($submit) || isset($keywords)) 
{ 
	doSearch($keywords); 
} 
else 
{ 
	getKeywords(); 
}

function getKeywords() 
{

?>

<html><head><title> Enter Search Keywords </title></head>

 <body bgcolor="#FFFFFF">
		<form name="frmKW" action="searchdocs.php" method="post"> 
		 <h1>Keyword Search</h1> 
			Enter keywords to search on: 
			 <input type="text" name="keywords" maxlength="100"> 
				<br><br><input type="submit" name="submit" value="Search">

		</form>
 </body>
</html>


<?php 

}
function doSearch($search_keywords) 
{ 
	$arrWords = explode(" ", $search_keywords);

if(sizeof($arrWords) == 0 || $search_keywords == "") 
{ 
	echo "You didn't enter any keywords<br>"; 
	echo "<a href='searchdocs.php'>Go Back</a>"; 
} 
else
{

// Connect to the database 
$dbhost = 'localhost'; 
$dbusername = 'root'; 
$dbpasswd = 'matrix'; 
$database_name = 'intranet';

$s = @mysql_connect($dbhost, $dbusername, $dbpasswd) 
     or die("Couldn't connect to database server");

		@mysql_select_db($database_name, $s) 
		 or die("Couldn't connect to database");

for($i = 0; $i < sizeof($arrWords); $i++) 
{ 
	$query = "select articleIds from searchWords where word = '{$arrWords[$i]}'"; 
	$filename = mysql_query($query);


if(mysql_num_rows($filename) > 0) 
{ 

// Get the id's of the articles 

	$row = mysql_fetch_array($filename); 
	$arrIds = explode(",", $row[0]); 
	$arrWhere = implode(" OR articleId = ", $arrIds);


	$aQuery = "select articleId, title, left(content, 100) as summary from articles where articleId = " . $arrWhere;
	$aResult = mysql_query($aQuery); 
	$count = 0;

//Each article returned from the select query is added to an associative array called $articles:

	$articles = array();

if(mysql_num_rows($aResult) > 0) 
{ 
	while($aRow = mysql_fetch_array($aResult)) 
{ 
	$articles[$count] = array ("articleId" => $aRow["articleId"], "title" => $aRow["title"], 
	"summary" => $aRow["summary"]); 

	$count++; 

} 
}

//At this point, the $articles associative array will contain all of the articles returned from the search.
if(isset($articles)) 
{ 

	$articles = array_unique($articles); 
	echo "<h1>" . sizeof($articles); 
	echo (sizeof($articles) == 1 ? " article" : " articles"); 
    echo " found:</h1>"; 

foreach($articles as $a => $value) 
{ 

?>

	<a href="?articleId=<?php echo $articles[$a]["articleId"]; ?>"> 
	<b><u><?php echo $articles[$a]["title"]; ?></u></b> 
	</a>

	<br><?php echo $articles[$a]["summary"] . "..."; ?><br>

	echo "<a href=\"".$filename."?articleId=".$articles[$a]."\">
	[URL unfurl="true"]http://localhost/intranet/".$filename."\?articleId\=[/URL]
	".$articles[$a]["articleId"]."</a>";

<br><br> 

<?php 

} 

}
else 
{ 

	echo "No results found for '$search_keywords'<br>"; 
	echo "<a href='searchdocs.php'>Go Back</a>"; 

} 

} 
} 
}
}
?>

..almost there..hang in there please
cheers
/rz
 
Ok, looking over the code I may have confused you with this line:

Code:
$filename = mysql_query(...);

Without knowing exactly what your mysql_query returns, I may not be able to provide you with the link code you require. However, I will again try :)

I have played slightly with your link code, I *think* this was what you were trying to do. Forgive me if it is a false assumption :)

This one will display a HTML link to article.php with the appropriate ID. The article's title will appear as the link's text.

Code:
<a href="article.php?articleId=<?php echo $articles[$a]["articleId"]; ?>"><b><u>
<?php echo $articles[$a]["title"]; ?></u></b></a>

This one displays a summary of the article, in text form.

Code:
<br><?php echo $articles[$a]["summary"]."..."; ?><br>

This one will also display a HTML link to article.php with the appropriate ID. This time the link's URL is displayed as the link text.

Code:
echo 
"<a href=\"article.php?articleId=".$articles[$a]."\">
[URL unfurl="true"]http://localhost/intranet/article.php?articleId=[/URL]
".$articles[$a]["articleId"]."</a>";

In short, The first and last code segments do essentially the same thing, but with different 'labels'. You should see something like this:

An Article Name
This is a short summary
of the article.

Where # is the appropriate ID number.
 
Okay this is the result from echoing the $query:
Code:
$query = "select articleIds from searchWords where word = '{$arrWords[$i]}'";

results select articleIds from searchWords where word = 'magellan'

and echoing $filename
Code:
$filename = mysql_query($query);

results in: Resource id #3


Seems that you still haven't quite yet understood, so I think this should explain my purpose whit this:

If I make a search for my document Magellan.doc It shows me the part of the information I saved to the database. The actual document is saved in a folder on the server. The documents title and a small explanation of what the text content is about is just for the database to know what to look for and where to find it. The actual Magellan.doc contains more information than the search alias. My point with this is to be able to find all types of document on the server. The url

article.php?articleId=#

is supposed to be the adress to take me to the actual file where it's saved on the server. The value article.php in the above link is supposed to be the value from your search result and it's not necessary to be an hmtl or php file.
So the file article.php doesn't exist, but when I save a file with that name and search Magellan it pops in the magellan link but has nothing to do with magellan document at all. whooow...hmhh...heavy breathing...can't be more clear than that.
What do you think maestro??..confusing??
 
in addtion..
forgot to mention the Resource Id#3 haven't a slightest idea what that referr to.
The table searchwords has 3 columns wordId, word, articleIds.
The articles table has 3 columns including articleId, title, content.
Magellan has articleIds 1 and wordId 1.

another thing.. do I really need all those double quotes..I mean are they all in the right place?
Code:
echo "<a href=\".$filename."?articleId=".$articles[$a]."\>"
	[URL unfurl="true"]http://localhost/intranet/".$filename."\?articleId\=[/URL]
	".$articles[$a]["articleId"]."</a>";
Why I wonder it this is how my result link looks like

1 article found:
Magellan Intranet is a great database
If you're after a top quality database, then you should consider Magellan and MySQL Intranet....
echo "" ".$articles[$a]["articleId"]."";
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top