Ok here's the code first, the problem will follow...
<?php
// Make sure a logged in user is querying
session_start();
if(!($_SESSION['sid'] == session_id())) {
die('You are not currently logged in. Please re-login and try your search again.');
}
// Set database information into variables - echo the image header along with HTML tags
$database="XXXXXXXX";
$server="mysql.XXXXXXXXX.com";
$dat_user="XXXXX";
$dat_pwd="XXXXXXX";
$dat_table="videodat";
print<<<_HTMLHEADER_
<html>
<head>
<title>TITLE HERE</title>
</head>
<body bgcolor="#FFFFFF" text="#000000" link="#660000" alink="#FF0000" vlink="#990000">
<img src="/members/images/vdat.gif" border="0"><br><br>
_HTMLHEADER_;
// Get the search variable from URL
$var = @$_GET['q'];
$trimmed = trim($var); //trim whitespace from the stored variable
// rows to return
$limit="10";
// check for an empty string and display a message.
if ($trimmed == "")
{
echo "<p>Please enter a search...</p>";
exit;
}
// check for a search parameter
if (!isset($var))
{
echo "<p>We dont seem to have a search parameter!</p>";
exit;
}
//connect to your database
if(!mysql_connect($server, $dat_user, $dat_pwd)) {
die("Unable to connect to MySQL server" . mysql_error());
}
//specify database
@mysql_select_db($database) or die("Unable to select database" . mysql_error());
// explode search term into array, count words
$exp_var = explode(" ", $var);
$wordcount = count($exp_var);
if($wordcount > 1) {
$query = "SELECT * FROM ($dat_table) WHERE (video_desc) RLIKE ('[[:<:]]$exp_var[0][[:>:]]')";
$crtwrd=2;
while($crtwrd <= $wordcount) {
$i = ($crtwrd - 1);
$query .= " OR (video_desc) RLIKE ('[[:<:]]$exp_var[$i][[:>:]]') OR (video_name) RLIKE ('[[:<:]]$exp_var[$i][[:>:]]')";
$crtwrd++;
}
}
elseif($wordcount == 1) {
$spvar = "[[:<:]]".$trimmed."[[:>:]]";
$query = "SELECT * FROM ($dat_table) WHERE (video_desc) RLIKE ('$spvar')";
}
else {
die("Script error! Unable to determine amount of search words! Contact webmaster for support.");
}
$numresults=mysql_query($query);
$numrows=mysql_num_rows($numresults);
// If we have no results, send the following message
if ($numrows == 0) {
echo "<h4>Results</h4>";
echo "<p>Sorry, your search: "" . $trimmed . "" returned zero results.</p>";
exit;
}
// next determine if s has been passed to script, if not use 0
if (empty($s)) {
$s=0;
}
// get results
$query .= " LIMIT $s,$limit";
$result = mysql_query($query) or die("Couldn't execute query!" . mysql_error());
// setup highlighting function
function highlight_words($content) {
global $searchwords;
foreach ($searchwords as $word) {
$content = eregi_replace(" ".$word." ", ' <b>'.$word.'</b> ', $content);
$content = eregi_replace(" ".$word."\.", ' <b>'.$word.'</b>.', $content);
$content = eregi_replace(" ".$word."!", ' <b>'.$word.'</b>!', $content);
$content = eregi_replace(" ".$word."\?", ' <b>'.$word.'</b>\?', $content);
$content = eregi_replace(" ".$word.",", ' <b>'.$word.'</b>,', $content);
// Don't forget upper-case instances
$wordup = ucfirst($word);
$content = ereg_replace($wordup." ", '<b>'.$wordup.'</b> ', $content);
}
return $content;
}
$searchwords = explode(" ", str_replace(array("-","*","~","\"","(",")","<",">","\\"),"",$trimmed));
// count word matches function
function count_words($content) {
global $searchwords;
$wordcount = 0;
$lowercasecontent = strtolower($content);
foreach($searchwords as $word) {
$firstword = explode(" ", $lowercasecontent, 2);
if((strcasecmp($firstword[0], $word) == 0)) {
$wordcount++;
}
$wordcount += substr_count($lowercasecontent, " ".$word." ");
$wordcount += substr_count($lowercasecontent, " ".$word."\.");
$wordcount += substr_count($lowercasecontent, " ".$word."!");
$wordcount += substr_count($lowercasecontent, " ".$word."\?");
$wordcount += substr_count($lowercasecontent, " ".$word.",");
}
return $wordcount;
}
// display what the person searched for
echo "<font face=\"Verdana, Arial\" size=\"3\"><b><u>Search results...</b></u><br><br>";
// begin to show results set
echo "You searched for: \"<b>" . $var . "</b>\"</font><font face=\"Arial, Verdana\" size=\"2\">";
$count = 1 + $s ;
// now you can display the results returned
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$row[score] = count_words($row[video_desc]);
$rows[] = $row;
}
uasort($rows, 'search_rank');
foreach($rows as $row) {
$title = $row["video_name"];
$desc = $row["video_desc"];
$path = $row["video_path"];
$category = $row["video_cat"];
$id = $row["id"];
$fsize = filesize("$path");
$prettydesc = highlight_words($row[video_desc]);
echo("<br><br><b>$count. <a href=\"http://www.XXXXXXXXXXXX.com/videodat/video.php?id=$id\" target=\"_blank\">$title</a></b> ($fsize Bytes) ($row[score] word matches) <br>$prettydesc ");
$count++ ;
}
// ranking function for use in uasort
function search_rank($a, $b) {
$ax = $a[score];
$bx = $b[score];
if($ax == $bx) {
return 0;
}
return ($ax > $bx) ? -1 : 1;
}
$currPage = (($s/$limit) + 1);
//break before paging
echo "<br />";
// next we need to do the links to other results
if ($s>=1) { // bypass PREV link if s is 0
$prevs=($s-$limit);
print "<br> <a href=\"$PHP_SELF?s=$prevs&q=$var\"><< Prev 10</a> ";
}
// calculate number of pages needing links
$pages=intval($numrows/$limit);
// $pages now contains int of pages needed unless there is a remainder from division
if ($numrows%$limit) {
// has remainder so add one page
$pages++;
}
// check to see if last page
if (!((($s+$limit)/$limit)==$pages) && $pages!=1) {
// not last page so give NEXT link
$news=$s+$limit;
echo "<br> <a href=\"$PHP_SELF?s=$news&q=$var\">Next 10 >></a>";
}
$a = $s + ($limit) ;
if ($a > $numrows) { $a = $numrows ; }
$b = $s + 1 ;
echo "<p>Showing results $b to $a of $numrows</p>";
//End HTML tags
print<<<_HTMLFOOTER_
</body>
</html>
_HTMLFOOTER_;
?>
So first of all, I am relatively new to PHP, so any kind of code critique would be met with open ears.
The script words just like it is supposed to except for one thing: The results are sorted over multiple pages. That is, if the search returns over 10 results, it ranks the first page based on number of matches, then the 2nd page will be organized the same way.. So my first page of results will go from say (4 matches) to (2 matches) and then for some reason when I go to the (NEXT 10 >) it will start at (4 matches) again..
If you need me to clarify, just ask, but my goal here is to have the search results ranked over all pages, not per page (obviously!)
Thanks for any and all help (and critique!) I am still learning PHP so I'm sure there are some things I'm doing wrong/weird.
--tgmsocal