Jump to content

Full Text Search with Pagination Class


Recommended Posts

I've used the Full Text search example from this site and added the pagination class from http://www.goodphptutorials.com/article/show/simple-php-mysql-pagination/1 but I'm stumbling where it actually breaks the page up into the prescribed number of page. Right now I have script set for 5 results per page and while I can get the total number of records in the search result set, I can't get the results to span over say 3 pages if there's 15 results. Can anyone tell me why? Be gentle.. I'm new to PHP.

 

<?php
require("pages.php");

// Full-Text Search Example
// Conect to the database.

$cnx = mysql_connect('host', 'uname', 'pword') or die ("Could not connect");
mysql_select_db('db',  $cnx) or die (mysql_error());
error_reporting(E_ALL | E_STRICT);

// Let's call some display data from the database before we begin /////////////////////////////////

$page = 1;

// how many records per page
$size = 5;

// we get the current page from $_GET
if (isset($_GET['page'])){
    $page = (int) $_GET['page'];
}

// create the pagination class
$pagination = new Pagination();
$pagination->setLink("search.php?cmd=search&words=$_GET[words]&mode=$_GET[mode]&page=%s");
$pagination->setPage($page);
$pagination->setSize($size);

// now use this SQL statement to get records from your table
$SQL = "SELECT * FROM sets, systems " . $pagination->getLimitSql();

// Create the search function: ////////////////////////////////////////////////////////////////////

function searchForm()
{

// Re-usable form /////////////////////////////////////////////////////////////////////////////////
  
// variable setup for the form. ///////////////////////////////////////////////////////////////////

  $searchwords = (isset($_GET['words']) ? htmlspecialchars(stripslashes($_REQUEST['words'])) : '');
  $normal = (($_GET['mode'] == 'normal') ? ' selected="selected"' : '' );
  $boolean = (($_GET['mode'] == 'boolean') ? ' selected="selected"' : '' );
  
  echo '<div align="center">';  
  echo '<form method="get" action="'.$_SERVER['PHP_SELF'].'">';
  echo '<input type="hidden" name="cmd" value="search" />';
  echo 'Search for: <input type="text" name="words" value="'.$searchwords.'" /> ';
  echo 'Mode: ';
  echo '<select name="mode">';
  echo '<option value="normal"'.$normal.'>Normal</option>';
  echo '<option value="boolean"'.$boolean.'>Boolean</option>';
  echo '</select> ';
  echo '<input type="submit" value="Search" />';
  echo '</form>';
  echo '</div>';
}


// Create the navigation switch ///////////////////////////////////////////////////////////////////

$cmd = (isset($_GET['cmd']) ? $_GET['cmd'] : '');

switch($cmd)
{
  default:
    echo '<h1>Search Database!</h1>';
    searchForm();
  
  break;
  
  
  case "search":
    searchForm();
//    echo '<h3>Search Results:</h3>';
    
    $searchstring = mysql_escape_string($_GET['words']);
/*
* To identify appropriate descriptions to display, we need to split the 
* search string up into individual words, and then show descriptions that
* contain any of the words.
* First, normalize search strings so all whitespace characters become spaces
* This should not affect mysql's interpretation of the string when used in
* a full-text search.
*/
$searchstring = trim(preg_replace('/\s+/', ' ', $searchstring));
//now make an array of the words, one word per array index
$words = explode(' ', $searchstring);
    switch($_GET['mode'])
    {
      case "normal":
        $sql = "SELECT set_category, set_subcategory, set_name, set_desc, set_desc2, 
               MATCH(set_name, set_desc, set_desc2) 
               AGAINST ('$searchstring') AS score FROM sets, set_category, set_subcategory 
               WHERE sets.set_category_id = set_category.set_category_id
               AND sets.set_subcategory_id = set_subcategory.set_subcategory_id
               AND MATCH(set_name, set_desc, set_desc2) 
               AGAINST ('$searchstring')
		   UNION
		   SELECT system_category, system_subcategory, system_name, system_desc, system_desc2, 
               MATCH(system_name, system_desc, system_desc2) 
               AGAINST ('$searchstring') AS score FROM systems, system_category, system_subcategory 
               WHERE systems.system_category_id = system_category.system_category_id
               AND systems.system_subcategory_id = system_subcategory.system_subcategory_id
               AND MATCH(system_name, system_desc, system_desc2) 
               AGAINST ('$searchstring') ORDER BY score DESC";
      break;
      
      case "boolean":
        $sql = "SELECT set_category, set_subcategory, set_name, set_desc, set_desc2, 
               MATCH(set_name, set_desc, set_desc2) 
               AGAINST ('$searchstring') AS score FROM sets, set_category, set_subcategory 
               WHERE sets.set_category_id = set_category.set_category_id
               AND sets.set_subcategory_id = set_subcategory.set_subcategory_id
               AND MATCH(set_name, set_desc, set_desc2) 
               AGAINST ('$searchstring' IN BOOLEAN MODE)
		   UNION
		   SELECT system_category, system_subcategory, system_name, system_desc, system_desc2, 
               MATCH(system_name, system_desc, system_desc2) 
               AGAINST ('$searchstring') AS score FROM systems, system_category, system_subcategory
               WHERE systems.system_category_id = system_category.system_category_id
               AND systems.system_subcategory_id = system_subcategory.system_subcategory_id
               AND MATCH(system_name, system_desc, system_desc2) 
               AGAINST ('$searchstring' IN BOOLEAN MODE) ORDER BY score DESC";
      break;
    } 
    
    // echo $sql;

    $result = mysql_query($sql) or die (mysql_error());

$num_rows = mysql_num_rows($result);

if (mysql_num_rows($result) > 0 ) {

   ob_start();
   /* I hate output buffering calls, but without redoing the database 
   * structure so that only real search results are returned, this is the 
   * only practical way to print a correct "search results found" number.
   */
    while($row = mysql_fetch_object($result))
    {

/*
* Begin determining if this result should even be here. Some should not,
* when search terms occur in description html markup only.
*/
$inText = false;
foreach($words AS $word)
{
	if(strpos(strtolower(strip_tags($row->set_name)), strtolower($word)) !== false)
	{
		$inText = true;
		break;
	}
}

// Description headings in the output /////////////////////////////////////////////////////////////
$description = array();
$set_desc = strip_tags($row->set_desc);
foreach($words AS $word)
{
	if(strpos(strtolower($set_desc), strtolower($word)) !== false)
	{
		$description[] = "<strong>Description 1:</strong> ".stripslashes($set_desc);
		$inText = true;
		break;
	}
}

$set_desc = strip_tags($row->set_desc2);
foreach($words AS $word)
{
	if(strpos(strtolower($set_desc), strtolower($word)) !== false)
	{
		$description[] = "<strong>Description 2:</strong> ".stripslashes($set_desc);
		$inText = true;
		break;
	}
}

/*
* Now all the text has been searched, and we know whether this result 
* contains search terms in plain text. If not, no need to continue 
* processing on it.
*/
if(! $inText)
{
	$num_rows--;
	continue;
}

if(count($description))
{
	$description = $description[0];
	for($i = 1; $i < count($description); $i++)
	{
		$description .= "<br>" . $description[$i];
	}
}
else 
{ 
	$description = "<font color=\"red\">No description found.</font>";
}

// Category headings in the output ////////////////////////////////////////////////////////////////
/*
if (!empty($row->set_category_id)) {
	$category = "<strong>Category:</strong> $row->set_category_id";
} else { }
if (!empty($row->set_subcategory_id)) {
	$subCategory = "<strong>Sub-category:</strong> $row->set_subcategory_id";
} else { }
*/
// Let's build the results here ///////////////////////////////////////////////////////////////////

      echo '<strong>Name: '. stripslashes(strip_tags($row->set_name)).'</strong><br />';
      echo 'Score: '. number_format($row->score, 1).'<br />';
      echo '<p>'.$description.'</p>';
  echo '<strong>Category:</strong> '.$row->set_category .' <strong>Subcategory:</strong> ' . $row->set_subcategory . '<br />';
      echo '<hr size="1" />';
    }

$results = ob_get_contents();
ob_end_clean();
echo '<h3>Search Results Found: '.$num_rows.'</h3>';
echo $results;

$pagination->setTotalRecords($num_rows);
$navigation = $pagination->create_links();
echo $navigation; // will draw our page navigation

//echo "<p>$num_rows Rows</p>";

	} else {
		echo "<h3>Oops!</h3><p>Sorry, there are no results to display. Try to broaden your search and try again.</p>";
}
  break;

}

?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.