Jump to content

Trying to build a simple site search with pagination


mikejs2010

Recommended Posts

Hi I have read through numerous forum posts and tried a number of examples, however either the tutorials did not cover everything or I just got lost

 

I can build a paginated results page using CS4 however the tutorial does not explain how you would impliment a search to produce the results this is the code from that example

 

<?php require_once('Connections/search_site.php'); 

if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  if (PHP_VERSION < 6) {
    $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  }

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}

$currentPage = $_SERVER["PHP_SELF"];

$maxRows_search = 10;
$pageNum_search = 0;
if (isset($_GET['pageNum_search'])) {
  $pageNum_search = $_GET['pageNum_search'];
}
$startRow_search = $pageNum_search * $maxRows_search;

mysql_select_db($database_search_site, $search_site);
$query_search = "SELECT * FROM articles ORDER BY id ASC";
$query_limit_search = sprintf("%s LIMIT %d, %d", $query_search, $startRow_search, $maxRows_search);
$search = mysql_query($query_limit_search, $search_site) or die(mysql_error());
$row_search = mysql_fetch_assoc($search);

if (isset($_GET['totalRows_search'])) {
  $totalRows_search = $_GET['totalRows_search'];
} else {
  $all_search = mysql_query($query_search);
  $totalRows_search = mysql_num_rows($all_search);
}
$totalPages_search = ceil($totalRows_search/$maxRows_search)-1;

$queryString_search = "";
if (!empty($_SERVER['QUERY_STRING'])) {
  $params = explode("&", $_SERVER['QUERY_STRING']);
  $newParams = array();
  foreach ($params as $param) {
    if (stristr($param, "pageNum_search") == false && 
        stristr($param, "totalRows_search") == false) {
      array_push($newParams, $param);
    }
  }
  if (count($newParams) != 0) {
    $queryString_search = "&" . htmlentities(implode("&", $newParams));
  }
}
$queryString_search = sprintf("&totalRows_search=%d%s", $totalRows_search, $queryString_search);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<body>
<?php

//include("header.php");
include("conf.php");
?>


    

<table border="0">
  <tr>
    <td><?php if ($pageNum_search > 0) { // Show if not first page ?>
        <a href="<?php printf("%s?pageNum_search=%d%s", $currentPage, 0, $queryString_search); ?>">First</a>
        <?php } // Show if not first page ?></td>
    <td><?php if ($pageNum_search > 0) { // Show if not first page ?>
        <a href="<?php printf("%s?pageNum_search=%d%s", $currentPage, max(0, $pageNum_search - 1), $queryString_search); ?>">Previous</a>
        <?php } // Show if not first page ?></td>
    <td><?php if ($pageNum_search < $totalPages_search) { // Show if not last page ?>
        <a href="<?php printf("%s?pageNum_search=%d%s", $currentPage, min($totalPages_search, $pageNum_search + 1), $queryString_search); ?>">Next</a>
        <?php } // Show if not last page ?></td>
    <td><?php if ($pageNum_search < $totalPages_search) { // Show if not last page ?>
        <a href="<?php printf("%s?pageNum_search=%d%s", $currentPage, $totalPages_search, $queryString_search); ?>">Last</a>
        <?php } // Show if not last page ?></td>
  </tr>
</table>
<table border="1" cellpadding="3" cellspacing="3">
  <tr>
    <td>id</td>
    <td>category</td>
    <td>title</td>
    <td>body</td>
    <td>rate</td>
  </tr>
  <?php do { ?>
    <tr>
      <td><?php echo $row_search['id']; ?></td>
      <td><?php echo $row_search['category']; ?></td>
      <td><?php echo $row_search['title']; ?></td>
      <td><?php echo $row_search['body']; ?></td>
      <td><?php echo $row_search['rate']; ?></td>
    </tr>
    <?php } while ($row_search = mysql_fetch_assoc($search)); ?>
</table>
</body>
</html>
<?php
mysql_free_result($search);
?>

 

How would I add a search box to provide the results

 

I created a simple search using

<?php

//include("header.php");
include("conf.php");
?>

<div id="container2">
  <div id="content"><br />
    <form action="index.php" method="get">
      Search Site:
      <input type="text" name="q" />
      <input type="submit" name="searchtext" class="submit-btn" src="btn.gif" alt="submit" title="submit" />
    </form>
    <br />
    <br />
<?php
if (count($_GET) > 0) {
$search.= trim(strtoupper($_GET['q']));

mysql_select_db ("db_search")
or die ("Cannot connect to the database");

//run query on database where search value is like table fields
$sql.= "select * from articles where ( ";
$sql .= " UPPER(title) like '%" . $search . "%' or ";
$sql .= " UPPER(category) like '%" . $search . "%' or ";
$sql .= " UPPER(body) like '%" . $search . "%'or ";
$sql .= ") order by category";

$q.= (mysql_query($sql));

$num_rows.= mysql_num_rows($q); ///check no of rows

// while there are rows echo output to produce page of results
if($num_rows>0){
while($d.= mysql_fetch_array($q)){
$id.= $d['id'];
$title.= $d['title'];
$category.= $d['category'];
$body.= $d['body'];

echo "<div clas.=\"response\"><p><strong>" . $title . "</strong></p>";
//include("resultsheader.php");
echo $id . ' - ';
echo '<br>';
echo 'Category: ' . $category . '<br>';
echo '<br>';
echo 'Body: ' . $body . '<hr>';
echo "</div>";
}
//end while loop

}else{
echo"<p>Sorry, no search result. Please change keywords and try again.</p>";
}//end if 

?>
  </div>
</div>

<?php
//include("footer.php");
?>

 

however this now gives me a parse error at the last line of code I have checked all the {} and ; and "" but it still doesn't work I have been reading and testing all day I can't belive there is no step by step guide to somthing that many people would want to use on their site, can somone either provide a step by step or a link I have classes and methods comming out of my ears...

 

thanks

m

First of all if you are wanting a certain amount on each page you are going to need to look into the LIMIT keyword for your MySQL statement. You can add that to your url GET string when calling the page and assign the link to each button very easily for seeing the next set or previous set of results.

 

Also please add indentation to your code... it is horrible to go through it without...

Thanks for the reply

 

<?php
//include("header.php");
include("conf.php");
?>
<div id="container2">
  <div id="content"><br />
    <form action="index.php" method="get">
      Search Site:
      <input type="text" name="q" />
      <input type="submit" name="searchtext" class="submit-btn" src="btn.gif" alt="submit" title="submit" />
    </form>
    <br />
    <br />
    <?php
if (count($_GET) > 0) {
	$search.= trim(strtoupper($_GET['q']));
	mysql_select_db ("db_search") or die ("Cannot connect to the database");

//run query on database where search value is like table fields
$sql.= "select * from articles where ( ";
$sql .= " UPPER(title) like '%" . $search . "%' or ";
$sql .= " UPPER(category) like '%" . $search . "%' or ";
$sql .= " UPPER(body) like '%" . $search . "%'or ";
$sql .= ") order by category";
$q.= (mysql_query($sql));
$num_rows.= mysql_num_rows($q); ///check no of rows

// while there are rows echo output to produce page of results
if($num_rows>0){
while($d.= mysql_fetch_array($q)){
	$id.= $d['id'];
	$title.= $d['title'];
	$category.= $d['category'];
	$body.= $d['body'];

	echo "<div clas.=\"response\"><p><strong>" . $title . "</strong></p>";
	//include("resultsheader.php");
	echo $id . ' - ';
	echo '<br>';
	echo 'Category: ' . $category . '<br>';
	echo '<br>';
	echo 'Body: ' . $body . '<hr>';
	echo "</div>";
}
//end while loop

}
else
{
echo"<p>Sorry, no search result. Please change keywords and try again.</p>";
}//end if 

?>
</div><!---- close container2 -->
</div><!---- close content -->
<?php
//include("footer.php");
?>

 

for now I would be happy to figure out the parse error and work on pagination later or I coulsd start again from scratch any idea how I would add search to the first piece of code instead of it just populating the whole table

I think the {} count may be off... Example:

 

Thanks for the reply

 

<?php
//include("header.php");
include("conf.php");
?>
<div id="container2">
  <div id="content"><br />
    <form action="index.php" method="get">
      Search Site:
      <input type="text" name="q" />
      <input type="submit" name="searchtext" class="submit-btn" src="btn.gif" alt="submit" title="submit" />
    </form>
    <br />
    <br />
    <?php
if (count($_GET) > 0) {                             // 1 open
	$search.= trim(strtoupper($_GET['q']));
	mysql_select_db ("db_search") or die ("Cannot connect to the database");

//run query on database where search value is like table fields
$sql.= "select * from articles where ( ";
$sql .= " UPPER(title) like '%" . $search . "%' or ";
$sql .= " UPPER(category) like '%" . $search . "%' or ";
$sql .= " UPPER(body) like '%" . $search . "%'or ";
$sql .= ") order by category";
$q.= (mysql_query($sql));
$num_rows.= mysql_num_rows($q); ///check no of rows

// while there are rows echo output to produce page of results
if($num_rows>0){                                                              // 2 open
while($d.= mysql_fetch_array($q)){                            // 3 open
	$id.= $d['id'];
	$title.= $d['title'];
	$category.= $d['category'];
	$body.= $d['body'];

	echo "<div clas.=\"response\"><p><strong>" . $title . "</strong></p>";
	//include("resultsheader.php");
	echo $id . ' - ';
	echo '<br>';
	echo 'Category: ' . $category . '<br>';
	echo '<br>';
	echo 'Body: ' . $body . '<hr>';
	echo "</div>";
}                                                                         // 2 open
//end while loop

}                                                                        // 1 open
else
{                                                                        // 2 open
echo"<p>Sorry, no search result. Please change keywords and try again.</p>";
}//end if                                                             // 1 open

?>
</div><!---- close container2 -->
</div><!---- close content -->
<?php
//include("footer.php");
?>

 

for now I would be happy to figure out the parse error and work on pagination later or I coulsd start again from scratch any idea how I would add search to the first piece of code instead of it just populating the whole table

 

That still leaves one { open. Hope this helps.

Thanks for that I knew it was somthing simple it now works, my next task is paginating the results although as i will be populating the database I could just add say 10 articles for each catagory so it doesn't create a massive list...

 

<?php
  include("header.php");
  include("conf.php");
?>

<div id="container2">
<div id="content">
<br />
<form action="index.php" method="GET">
  Search Site:
  <input type="text" name="q" />
  <input type="submit" name="Search" src="btn.gif" alt="submit" title="submit" />
</form>
<br />
<br />
<?php
  if (count($_GET) > 0) {
  $search = trim(strtoupper($_GET['q']));
  
  mysql_select_db ("db_search")
  or die ("Cannot connect to the database");
  
  //run query on database where search value is like table fields
  $sql = "SELECT * FROM articles WHERE ( ";
  $sql .= " UPPER(title) LIKE '%" . $search . "%' OR ";
  $sql .= " UPPER(category) LIKE '%" . $search . "%' OR ";
  $sql .= " UPPER(body) LIKE '%" . $search . "%' ";
  $sql .= ") order by category";
  
  $q = (mysql_query($sql));
// echo $q;
  $num_rows = mysql_num_rows($q); ///check no of rows
  
  // while there are rows echo output to produce page of results
  if($num_rows>0){
	 while($d = mysql_fetch_array($q)){
	 $id = $d['id'];
	 $title = $d['title'];
  	 $category = $d['category'];
	 $body = $d['body'];
  
  echo "<div class=\"response\"><p><strong>" . $title . "</strong></p>";
  echo '<br>';
  echo 'Category: ' . $category . '<br>';
  echo '<br>';
  echo 'Body: ' . $body . '<hr>';
  echo "</div>";
}
//end while loop
  }

else
{
	 echo"<p>Sorry, no search result. Please change keywords and try again.</p>";
}//end if 
}
?>
  </div>
</div>
<?php
include ("footer.php");
?>

 

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.