Jump to content

Error when doing SEARCH page


thientanchuong

Recommended Posts

I create more 3 files called config1.php, common1.php and database1.php respectively in order to test. All of them have the same code from config.php, common.php and database.php

 

next, I use include function to called config1 file (config1.php) in search.php and remove sesstion_start() in config1.php file, put the session_start function in database1.php and common1.php following the advise, then test:

 

search_code5.jpg

 

The error message said that I do not need the sesstion_start() in both database1.php and common1.php, so I remmove the function. Finally, there is no error message when I test :

 

search_fix1.jpg

 

But error paging is still appearing, when I click on page 2 for example, the page turns out nothing again:

 

search_error1.jpg

 

I noticed that the address bar which is

 

   

 

is missing search value, so address bar shoud show the link:

 

   

 

How can I add the search value after http://yoongda.com/search.php?page=2& such as search=a ?

 

this is my common1.php which contains  paging function.

 

[code]<?php
/*
Contain the common functions 
required in shop and admin pages
*/
require_once 'config1.php';
require_once 'database1.php';

/*
Make sure each key name in $requiredField exist
in $_POST and the value is not empty
*/
function checkRequiredPost($requiredField) {
$numRequired = count($requiredField);
$keys        = array_keys($_POST);

$allFieldExist  = true;
for ($i = 0; $i < $numRequired && $allFieldExist; $i++) {
	if (!in_array($requiredField[$i], $keys) || $_POST[$requiredField[$i]] == '') {
		$allFieldExist = false;
	}
}

return $allFieldExist;
}

function getShopConfig()
{
// get current configuration
$sql = "SELECT sc_name, sc_address, sc_phone, sc_email, sc_shipping_cost, sc_order_email, cy_symbol 
		FROM tbl_shop_config sc, tbl_currency cy
		WHERE sc_currency = cy_id";
$result = dbQuery($sql);
$row    = dbFetchAssoc($result);

    if ($row) {
        extract($row);

        $shopConfig = array('name'           => $sc_name,
                            'address'        => $sc_address,
                            'phone'          => $sc_phone,
                            'email'          => $sc_email,
			    'sendOrderEmail' => $sc_order_email,
                            'shippingCost'   => $sc_shipping_cost,
                            'currency'       => $cy_symbol);
    } else {
        $shopConfig = array('name'           => '',
                            'address'        => '',
                            'phone'          => '',
                            'email'          => '',
			    'sendOrderEmail' => '',
                            'shippingCost'   => '',
                            'currency'       => '');    
    }

return $shopConfig;						
}

function displayAmount($amount)
{
global $shopConfig;
return $shopConfig['currency'] . number_format($amount);
}

/*
Join up the key value pairs in $_GET
into a single query string
*/
function queryString()
{
$qString = array();

foreach($_GET as $key => $value) {
	if (trim($value) != '') {
		$qString[] = $key. '=' . trim($value);
	} else {
		$qString[] = $key;
	}
}

$qString = implode('&', $qString);

return $qString;
}

/*
Put an error message on session 
*/
function setError($errorMessage)
{
if (!isset($_SESSION['plaincart_error'])) {
	$_SESSION['plaincart_error'] = array();
}

$_SESSION['plaincart_error'][] = $errorMessage;

}

/*
print the error message
*/
function displayError()
{
if (isset($_SESSION['plaincart_error']) && count($_SESSION['plaincart_error'])) {
	$numError = count($_SESSION['plaincart_error']);

	echo '<table id="errorMessage" width="550" align="center" cellpadding="20" cellspacing="0"><tr><td>';
	for ($i = 0; $i < $numError; $i++) {
		echo '&#8226; ' . $_SESSION['plaincart_error'][$i] . "<br>\r\n";
	}
	echo '</td></tr></table>';

	// remove all error messages from session
	$_SESSION['plaincart_error'] = array();
}
}

/**************************
Paging Functions
***************************/

function getPagingQuery($sql, $itemPerPage = 10)
{
if (isset($_GET['page']) && (int)$_GET['page'] > 0) {
	$page = (int)$_GET['page'];
} else {
	$page = 1;
}

// start fetching from this row number
$offset = ($page - 1) * $itemPerPage;

return $sql . " LIMIT $offset, $itemPerPage";
}

/*
Get the links to navigate between one result page to another.
Supply a value for $strGet if the page url already contain some
GET values for example if the original page url is like this :

http://www.yoongda.com/index.php?c=12

use "c=12" as the value for $strGet. But if the url is like this :

http://yoongda.com/index.php

then there's no need to set a value for $strGet


*/
function getPagingLink($sql, $itemPerPage = 10, $strGet = '')
{
$result        = dbQuery($sql);
$pagingLink    = '';
$totalResults  = dbNumRows($result);
$totalPages    = ceil($totalResults / $itemPerPage);

// how many link pages to show
$numLinks      = 10;


// create the paging links only if we have more than one page of results
if ($totalPages > 1) {

	$self = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] ;


	if (isset($_GET['page']) && (int)$_GET['page'] > 0) {
		$pageNumber = (int)$_GET['page'];
	} else {
		$pageNumber = 1;
	}

	// print 'previous' link only if we're not
	// on page one
	if ($pageNumber > 1) {
		$page = $pageNumber - 1;
		if ($page > 1) {
			$prev = " <a href=\"$self?page=$page&$strGet/\">[Prev]</a> ";
		} else {
			$prev = " <a href=\"$self?$strGet\">[Prev]</a> ";
		}	

		$first = " <a href=\"$self?$strGet\">[First]</a> ";
	} else {
		$prev  = ''; // we're on page one, don't show 'previous' link
		$first = ''; // nor 'first page' link
	}

	// print 'next' link only if we're not
	// on the last page
	if ($pageNumber < $totalPages) {
		$page = $pageNumber + 1;
		$next = " <a href=\"$self?page=$page&$strGet\">[Next]</a> ";
		$last = " <a href=\"$self?page=$totalPages&$strGet\">[Last]</a> ";
	} else {
		$next = ''; // we're on the last page, don't show 'next' link
		$last = ''; // nor 'last page' link
	}

	$start = $pageNumber - ($pageNumber % $numLinks) + 1;
	$end   = $start + $numLinks - 1;		

	$end   = min($totalPages, $end);

	$pagingLink = array();
	for($page = $start; $page <= $end; $page++)	{
		if ($page == $pageNumber) {
			$pagingLink[] = " $page ";   // no need to create a link to current page
		} else {
			if ($page == 1) {
				$pagingLink[] = " <a href=\"$self?$strGet\">$page</a> ";
			} else {	
				$pagingLink[] = " <a href=\"$self?page=$page&$strGet\">$page</a> ";
			}	
		}

	}

	$pagingLink = implode(' | ', $pagingLink);

	// return the page navigation link
	$pagingLink = $first . $prev . $pagingLink . $next . $last;
}

return $pagingLink;
}
?>

[/code]

 

database1.php

 

<?php
require_once 'config1.php';

$dbConn = mysql_connect ($dbHost, $dbUser, $dbPass) or die ('MySQL connect failed. ' . mysql_error());
mysql_select_db($dbName) or die('Cannot select database. ' . mysql_error());

function dbQuery($sql)
{
$result = mysql_query($sql) or die(mysql_error());

return $result;
}

function dbAffectedRows()
{
global $dbConn;

return mysql_affected_rows($dbConn);
}

function dbFetchArray($result, $resultType = MYSQL_NUM) {
return mysql_fetch_array($result, $resultType);
}

function dbFetchAssoc($result)
{
return mysql_fetch_assoc($result);
}

function dbFetchRow($result) 
{
return mysql_fetch_row($result);
}

function dbFreeResult($result)
{
return mysql_free_result($result);
}

function dbNumRows($result)
{
return mysql_num_rows($result);
}

function dbSelect($dbName)
{
return mysql_select_db($dbName);
}

function dbInsertId()
{
return mysql_insert_id();
}
?>

 

config1.php

 

<?php
ini_set('display_errors', 'On');
//ob_start("ob_gzhandler");
error_reporting(E_ALL);

// database connection config
$dbHost = 'yoongda.db.xxxxx.hostedresource.com';
$dbUser = 'yoongda';
$dbPass = 'xxxxx';
$dbName = 'yoongda';

// setting up the web root and server root for
// this shopping cart application
$thisFile = str_replace('\\', '/', __FILE__);
$docRoot = $_SERVER['DOCUMENT_ROOT'];

$webRoot  = str_replace(array($docRoot, 'library/config1.php'), '', $thisFile);
$srvRoot  = str_replace('library/config1.php', '', $thisFile);

define('WEB_ROOT', $webRoot);
define('SRV_ROOT', $srvRoot);

// these are the directories where we will store all
// category and product images
define('CATEGORY_IMAGE_DIR', 'images/category/');
define('PRODUCT_IMAGE_DIR',  'images/product/');

// some size limitation for the category
// and product images

// all category image width must not 
// exceed 75 pixels
define('MAX_CATEGORY_IMAGE_WIDTH', 75);

// do we need to limit the product image width?
// setting this value to 'true' is recommended
define('LIMIT_PRODUCT_WIDTH',     true);

// maximum width for all product image
define('MAX_PRODUCT_IMAGE_WIDTH', 300);

// the width for product thumbnail
define('THUMBNAIL_WIDTH',         75);

if (!get_magic_quotes_gpc()) {
if (isset($_POST)) {
	foreach ($_POST as $key => $value) {
		$_POST[$key] =  trim(addslashes($value));
	}
}

if (isset($_GET)) {
	foreach ($_GET as $key => $value) {
		$_GET[$key] = trim(addslashes($value));
	}
}	
}

// since all page will require a database access
// and the common library is also used by all
// it's logical to load these library here
require_once 'database1.php';
require_once 'common1.php';

// get the shop configuration ( name, addres, etc ), all page need it
$shopConfig = getShopConfig();
?>

 

and my search page : search.php

 

<form action="search.php" method="get">
<input name="search" type="text"/>
<input name="searchSubmit" type="submit" value="Search"/>
</form>

<?php
      // Get the search variable from URL

      $var = @$_GET['search'] ;
      $trimmed = trim($var); //trim whitespace from the stored variable

    // 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 ** EDIT REQUIRED HERE **
    include'library/config1.php';

    // Build SQL Query 
    $query = "select * from tbl_product where pd_name like \"%$trimmed%\" order by pd_id"; // EDIT HERE and specify your table and field names for the SQL query

    $numresults=mysql_query($query);
    $numrows=mysql_num_rows($numresults);

    // If we have no results, offer a google search as an alternative

    if ($numrows == 0)
      {
      echo "<h4>Results</h4>";
      echo "<p>Sorry, your search: "" . $trimmed . "" returned zero results</p>";

    // google
    echo "<p>Please, try again or <a href=\"http://www.google.com/search?search="
      . $trimmed . "\" target=\"_blank\" title=\"Look up
      " . $trimmed . " on Google\">Click here</a> to try the
      search on google</p>";
      }

    // next determine if s has been passed to script, if not use 0
      if (empty($s)) {
      $s=0;
      }

    // display what the person searched for
    echo "<p>You searched for: "" . $var . ""</p>";
    ?>
    
   <?php
if (!defined('WEB_ROOT')) {
exit;
}

$productsPerRow = 2;
$productsPerPage = 4;

$sql = "select * from tbl_product where pd_name like \"%$trimmed%\" order by pd_id";
$result     = dbQuery(getPagingQuery($sql, $productsPerPage));
$pagingLink = getPagingLink($sql, $productsPerPage);
$numProduct = dbNumRows($result);

// the product images are arranged in a table. to make sure
// each image gets equal space set the cell width here
$columnWidth = (int)(100 / $productsPerRow);
?>
<table width="100%" border="0" cellspacing="0" cellpadding="20">
<?php 
if ($numProduct > 0 ) {

$i = 0;
while ($row = dbFetchAssoc($result)) {

	extract($row);
	if ($pd_thumbnail) {
		$pd_thumbnail = WEB_ROOT . 'images/product/' . $pd_thumbnail;
	} else {
		$pd_thumbnail = WEB_ROOT . 'images/no-image-small.png';
	}

	if ($i % $productsPerRow == 0) {
		echo '<tr>';
	}

	// format how we display the price
	$pd_price = displayAmount($pd_price);

	echo "<td width=\"$columnWidth%\" align=\"center\"><a href=\"index.php?c=$cat_id&p=$pd_id" . "\"><img src=\"$pd_thumbnail\" border=\"0\" width=\"70\" height=\"100\" ><br>$pd_name</a><br>Price : $pd_price";

	// if the product is no longer in stock, tell the customer
	if ($pd_qty <= 0) {
		echo "<br>Out Of Stock";
	}

	echo "</td>\r\n";

	if ($i % $productsPerRow == $productsPerRow - 1) {
		echo '</tr>';
	}

	$i += 1;
}

if ($i % $productsPerRow > 0) {
	echo '<td colspan="' . ($productsPerRow - ($i % $productsPerRow)) . '"> </td>';
}

} else {
?>
<tr><td width="100%" align="center" valign="center">No products in this category</td></tr>
<?php	
}	
?>
</table>
<p align="center"><?php echo $pagingLink; ?></p>

 

I have tried to put 'search = $var' on $strGet in common1.php but it not working.

 

How can I add the search value after http://yoongda.com/search.php?page=2& such as search=a  ?

 

Looking for fixing the code

Link to comment
Share on other sites

Your function for pagination takes a parameter for it:

 

Change this:

$pagingLink = getPagingLink($sql, $productsPerPage);

 

to:

$pagingLink = getPagingLink($sql, $productsPerPage, "search=" . $_GET['search']);

 

 

And in the future, we really do not need screen shots for most problems. Thanks!

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.