Jump to content

Recommended Posts

Hi All,

 

I am trying to get this code working for my advanced search page. I keep getting an error:

 

Parse error: syntax error, unexpected $end in /home/rach99/public_html/client/search_adv.php on line 298

 

Which i researched and it said a bracket is missing. but i can't seem to work out from where?

 

This code was working as a normal search, this is the new code i added:

 

 

if (isset($_GET['search'])) {
  $query_sub = "";
  
  //set a flag to use if you need a comma
  $comma_flag = 0;
  //see if 'name' is not blank
  $trimmed = trim($_GET['name']);
  if ($trimmed != "") {
    $query_sub .= "tassearch.ResName LIKE '%$trimmed%'";
    $comma_flag = 1;
  }
  $trimmed = trim($_GET['cuisine']);
  if ($trimmed != "") {
    if ($comma_flag == 1) {
      $query_sub .= " AND ";
    }
    $query_sub .= "tascuisine.ResCuisine LIKE '%$trimmed%'";
    $comma_flag = 1;
  }
  $trimmed = trim($_GET['suburb']);
  if ($trimmed != "") {
    if ($comma_flag == 1) {
      $query_sub .= " AND ";
    }
    $query_sub .= "tassearch.ResSuburb LIKE '%$trimmed%'";
}
$query = "SELECT COUNT(*)
          FROM `{$tablename}`
          WHERE {$query_sub}`
          ORDER BY `{$ordercolumn}`";

 

This is it added to my old code:

 

 
<?php
// Set up some vars to use:
$tablename = 'tassearch'; // Change to the table to search
$searchcolumn = 'ResName'; // Change to the column to search
$searchcolumnb = 'ResSuburb';
$searchcolumna = 'ResCuisine';
$ordercolumn = 'ResName'; // Change to the column to order by
?>
<P>Welcome to example</P>

<?php

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

// If s is sent, then grab it.  If it's less than 0, make it 0 <!-- s;) --><img src=\"{SMILIES_PATH}/icon_wink.gif\" alt=\"\" title=\"Wink\" /><!-- s;) -->
  $s = 0;
  if(isset($_GET['s']))
  {
      $s = $_GET['s'];
      if($s < 0)
          $s = 0;
  }

// rows to return
$limit=10;

// check for an empty string and display a message.
if ($trimmed == "")
  {
  echo "<p>Please enter a search...</p>";
  exit;
  }

// secure the "trimmed" value
$trimmed = mysql_real_escape_string($trimmed);

// check for a search parameter
if (!isset($var))
  {
  echo "<p>We dont seem to have a search parameter!</p>";
  exit;
  }
  
  if (isset($_GET['search'])) {
  $query_sub = "";
  
  //set a flag to use if you need a comma
  $comma_flag = 0;
  //see if 'name' is not blank
  $trimmed = trim($_GET['name']);
  if ($trimmed != "") {
    $query_sub .= "tassearch.ResName LIKE '%$trimmed%'";
    $comma_flag = 1;
  }
  $trimmed = trim($_GET['cuisine']);
  if ($trimmed != "") {
    if ($comma_flag == 1) {
      $query_sub .= " AND ";
    }
    $query_sub .= "tascuisine.ResCuisine LIKE '%$trimmed%'";
    $comma_flag = 1;
  }
  $trimmed = trim($_GET['suburb']);
  if ($trimmed != "") {
    if ($comma_flag == 1) {
      $query_sub .= " AND ";
    }
    $query_sub .= "tassearch.ResSuburb LIKE '%$trimmed%'";
}
$query = "SELECT COUNT(*)
          FROM `{$tablename}`
          WHERE {$query_sub}`
          ORDER BY `{$ordercolumn}`";
          
// Build SQL Query  
$query = "SELECT COUNT(*)
          FROM `{$tablename}`
          WHERE `{$searchcolumn}` LIKE '%$trimmed%' or `{$searchcolumnb}` LIKE '%$trimmed%'
          ORDER BY `{$ordercolumn}`"; // EDIT HERE and specify your table and field names for the SQL query

$sql = "SELECT a.tascuisine, t.ResName
        FROM tascuisine a
            INNER JOIN linktable lt ON a.CusId = lt.FK_CusId
            INNER JOIN tablesearch t ON lt.FK_ResNameId = t.ResNameId
        WHERE a.CusId = $selectedCusId";


$rslt=mysql_query($query) or die('MySQL Error: ' . mysql_error());
$numrows = mysql_result($rslt, 0, 0);
@mysql_free_result($rslt);

// 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>";
}

// get results
  $query = "SELECT *
            FROM `{$tablename}`
            WHERE `{$searchcolumn}` LIKE '%{$trimmed}%' or `{$searchcolumnb}` LIKE '%{$trimmed}%'
            ORDER BY `{$ordercolumn}`
            LIMIT {$s}, {$limit}";
            
            
  $result = mysql_query($query) or die("Couldn't execute query");

// display what the person searched for
echo "<p>You searched for: "" . $var . ""</p>";

// begin to show results set
echo "<p>Results</p>";
$count = 1 + $s ;
  
while ($row = mysql_fetch_array($result)) {
  $link = $row['ResLink'];
  $link_title = $row['ResName'];

  echo $count . '.) <a href="' . $link . '">' . $link_title . '</a><br />';
  $count++;
}

$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 " <a href=\"$PHP_SELF?s=$prevs&q=$var\"><<
  Prev 10</a>&nbsp ";
  }

// 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 " <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>";
  
?> 

 

Any help would be great!

 

Thanks

 

Rachael

Link to comment
https://forums.phpfreaks.com/topic/90007-php-search-code-problem/
Share on other sites

Thanks :D

 

Problem is now it just isn't working. When i click search it just shows my search.adv.php page without any results. Did you see anything else i missed? I will post my form below in case my method is wrong.

 

<form action="search_adv.php" method="get" name="search">

 

name <input name="name" type="text" value="" size="15">

cuisine <input name="cuisine" type="text" value="" size="15">

suburb <input name="suburb" type="text" value="" size="15">

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

 

</form>

 

should i be placing my php inside my actual form page for this type of search?

 

 

Here is a copy commented up with my suggestions. Any line with a double pound (##) can be deleted:

 

<P>Welcome to example</P>

<?php
## Moved these down to keep PHP together (purely cosmetic)
  // Set up some vars to use:
  $tablename = 'tassearch'; // Change to the table to search
#  $searchcolumn = 'ResName'; // Change to the column to search
#  $searchcolumnb = 'ResSuburb';
#  $searchcolumna = 'ResCuisine';
  //Search colunmns and their matching form item name
  $where_parts = array(
    'name' => 'ResName',
    'cuisine' => 'ResCuisine',
    'suburb' => 'ResSuburb',
  );
  $ordercolumn = 'ResName'; // Change to the column to order by

## You cahnge the value of $trimmed below, so this is pointless 
## and will actually prevent your script from working 
##  // Get the search variable from URL
##  $var = $_GET['q'] ;
##  $trimmed = trim($var); //trim whitespace from the stored variable

  // If s is sent, then grab it.  If it's less than 0, make it 0 <!-- s;) --><img src=\"{SMILIES_PATH}/icon_wink.gif\" alt=\"\" title=\"Wink\" /><!-- s;) -->
##  $s = 0;
##  if(isset($_GET['s']))
##  {
##      $s = $_GET['s'];
##      if($s < 0)
##          $s = 0;
##  }
## Shorter version, does the same thing
  $s = ($_GET['s'] > 0) ? $_GET['s'] : 0;


  // rows to return
  $limit = 10;

## You don't use this variable, so this is pointless 
## and will actually prevent your script from working 
##  // check for an empty string and display a message.
##  if ($trimmed == "")
##  {
##    echo "<p>Please enter a search...</p>";
##    exit;
##  }
##
##  // secure the "trimmed" value
##  $trimmed = mysql_real_escape_string($trimmed);
## 
##// check for a search parameter
##if (!isset($var))
##  {
##  echo "<p>We dont seem to have a search parameter!</p>";
##  exit;
##  }
  
  if (isset($_GET['search'])) {
## A better way to do query_sub is with an array && implode, no need for comma_flag then
## Also, since it's the same code over and over, it's easier to manage with a loop
    $query_sub = array();
    $get_vars = array();
    foreach($where_parts as $form_key => $mysql_key){
      if(strlen(trim($_GET[$form_key]))){
        $query_sub[] = "`{$mysql_key}` LIKE '%".mysql_real_escape_string(trim($_GET[$form_key]))."%'";
        $get_vars[$form_key] = trim($_GET[$form_key);
      }
    }      

##    //set a flag to use if you need a comma
##    $comma_flag = 0;
##    //see if 'name' is not blank
##    $trimmed = mysql_real_escape_string(trim($_GET['name']));
##    if ($trimmed != "")
##      $query_sub .= "tassearch.ResName LIKE '%$trimmed%'";
##  $trimmed = trim($_GET['cuisine']);
##  if ($trimmed != "") {
##    if ($comma_flag == 1) {
##      $query_sub .= " AND ";
##    }
##    $query_sub .= "tascuisine.ResCuisine LIKE '%$trimmed%'";
##    $comma_flag = 1;
##  }
##  $trimmed = trim($_GET['suburb']);
##  if ($trimmed != "") {
##    if ($comma_flag == 1) {
##      $query_sub .= " AND ";
##    }
##    $query_sub .= "tassearch.ResSuburb LIKE '%$trimmed%'";
  }

  // Build SQL Query  
  $query = "SELECT * FROM `{$tablename}`";
  if(count($query_sub))
    $query .= " WHERE ".implode(' OR ',$query_sub);
  $query .= " ORDER BY `{$ordercolumn}` LIMIT {$s},{$limit}";
          
##// Build SQL Query  
##$query = "SELECT COUNT(*)
##          FROM `{$tablename}`
##          WHERE `{$searchcolumn}` LIKE '%$trimmed%' or `{$searchcolumnb}` LIKE '%$trimmed%'
##          ORDER BY `{$ordercolumn}`"; // EDIT HERE and specify your table and field names for the SQL query
## 
##$sql = "SELECT a.tascuisine, t.ResName
##        FROM tascuisine a
##            INNER JOIN linktable lt ON a.CusId = lt.FK_CusId
##            INNER JOIN tablesearch t ON lt.FK_ResNameId = t.ResNameId
##        WHERE a.CusId = $selectedCusId";


  $rslt = mysql_query($query) or die('MySQL Error: ' . mysql_error());
  $numrows = mysql_num_rows($rslt);

  // 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>";
  }
  else
  {
##    // get results
##  $query = "SELECT *
##            FROM `{$tablename}`
##            WHERE `{$searchcolumn}` LIKE '%{$trimmed}%' or `{$searchcolumnb}` LIKE '%{$trimmed}%'
##            ORDER BY `{$ordercolumn}`
##            LIMIT {$s}, {$limit}";
##            
##            
##  $result = mysql_query($query) or die("Couldn't execute query");

## Where is this person stuff coming from?
##// display what the person searched for
##echo "<p>You searched for: "" . $var . ""</p>";

  // begin to show results set
  echo "<p>Results</p>";
  $count = 1 + $s ;
  
  while ($row = mysql_fetch_array($rslt)) {
    $link = $row['ResLink'];
    $link_title = $row['ResName'];
   
    echo $count . '.) <a href="' . $link . '">' . $link_title . '</a><br />';
    $count++;
  }

  $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 " <a href=\"?s={$prevs}&".http_build_query($get_vars)."\"><< Prev 10</a>&nbsp ";
  }

  // calculate number of pages needing links
  $pages=ceil($numrows/$limit);

## ceil takes care of this
##  // $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) {
  if($s + $limit < $numrows){
    // not last page so give NEXT link
    $next = $s + $limit;
    print " <a href=\"?s={$next}&".http_build_query($get_vars)."\">Next 10 >></a>";
  }

  $a = $s + $limit;
  if($a > $numrows)
    $a = $numrows;
  echo "<p>Showing results ".($s + 1)." to {$a} of {$numrows}</p>";
?>

THANK YOU SO MUCH!

 

Works perfectly.

 

My ResCuisine is located in a differen table though, so it only works when i delete it from the list.

 

Do i set up another var and add that to the query? or is there and easier way to link it. i have tried a few things without results.

 

Thanks again, i really appreciate your help with all this :D

CREATE TABLE `tascuisine` (

  `CusId` int(11) NOT NULL auto_increment,

  `ResCuisine` text NOT NULL,

  PRIMARY KEY  (`CusId`)

) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;

 

 

INSERT INTO `tascuisine` VALUES (1, 'Seafood');

INSERT INTO `tascuisine` VALUES (2, 'Indian');

INSERT INTO `tascuisine` VALUES (3, 'Asian');

INSERT INTO `tascuisine` VALUES (4, 'Australian');

INSERT INTO `tascuisine` VALUES (5, 'European');

 

 

CREATE TABLE `taslinktable` (

  `FK_ResId` int(11) NOT NULL,

  `FK_CusId` int(11) NOT NULL,

  PRIMARY KEY  (`FK_ResId`,`FK_CusId`)

) ENGINE=MyISAM DEFAULT CHARSET=latin1;

 

 

INSERT INTO `taslinktable` VALUES (1, 1);

INSERT INTO `taslinktable` VALUES (2, 1);

INSERT INTO `taslinktable` VALUES (3, 1);

INSERT INTO `taslinktable` VALUES (3, 3);

INSERT INTO `taslinktable` VALUES (4, 1);

INSERT INTO `taslinktable` VALUES (4, 3);

INSERT INTO `taslinktable` VALUES (4, 4);

INSERT INTO `taslinktable` VALUES (6, 1);

 

CREATE TABLE `tassearch` (

  `ResId` int(11) NOT NULL auto_increment,

  `ResName` text NOT NULL,

  `ResSuburb` text NOT NULL,

  `ResLink` text NOT NULL,

  PRIMARY KEY  (`ResId`)

) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=11 ;

 

 

INSERT INTO `tassearch` VALUES (1, 'Hogs Breath Cafe', 'Hobart', 'hogs_breath.php');

INSERT INTO `tassearch` VALUES (2, 'Fish Frenzy', 'Hobart', 'fish_frenzy.php');

INSERT INTO `tassearch` VALUES (3, 'High Tide Waterfront Restaurant', 'Devonport', 'high_tide.php');

INSERT INTO `tassearch` VALUES (4, 'Marti Zuccos', 'North Hobart', 'marti_zuccos.php');

INSERT INTO `tassearch` VALUES (5, 'The Spice', 'Sandy Bay', 'the_spice.php');

INSERT INTO `tassearch` VALUES (6, 'Ball And Chain Grill', 'Hobart', 'ball_chain_grill.php');

INSERT INTO `tassearch` VALUES (7, 'Hallams Waterfront', 'Launceston', 'hallams_waterfront.php');

INSERT INTO `tassearch` VALUES (8, 'JJ''s Bakery And Old Mill Cafe', 'Longford', 'jjs_bakery_old_mill_cafe.php');

INSERT INTO `tassearch` VALUES (9, 'Kelley''s Seafood Restaurant', 'Battery Point', 'kelleys_seafood_restaurant.php');

INSERT INTO `tassearch` VALUES (10, 'Stillwater River Cafe', 'Launceston', 'stillwater.php');

 

Try this out:

 

<P>Welcome to example</P>
<?php
  //Set Start 
  $s = ($_GET['s'] > 0) ? $_GET['s'] : 0;

  //Rows to return
  $limit = 10;

  //Copy GET vars for later
  $where = array();
  $get = array();
  if (isset($_GET['search'])) {
    //name
    if(strlen(trim($_GET['name']))){
      $get['name'] = trim($_GET['name');
      $where[] = "`ResName` LIKE '%".mysql_real_escape_string($get['name'])."%'";
    }
    //suburb
    if(strlen(trim($_GET['suburb']))){
      $get['suburb'] = trim($_GET['suburb');
      $where[] = "`ResSuburb` LIKE '%".mysql_real_escape_string($get['suburb'])."%'";
    }
    //cuisine
    if(strlen(trim($_GET['cuisine']))){
      $get['cuisine'] = trim($_GET['cuisine');
      $where[] = "`ResId` IN (".
                   "SELECT `FK_ResId` FROM `taslinktable` WHERE `FK_CusId` IN (".
                     "SELECT `CusId` FROM `tascuisine` WHERE `ResCuisine` LIKE '%".mysql_real_escape_string($get['cuisine'])."%'"
                   ")".
                 ")";
    }
  }

  // Build SQL Query  
  $query = "SELECT * FROM `tassearch`";
  if(count($where))
    $query .= " WHERE ".implode(' OR ',$where);
  $query .= " ORDER BY `ResName` LIMIT {$s},{$limit}";

  $rslt = mysql_query($query) or die('MySQL Error: ' . mysql_error());
  $numrows = mysql_num_rows($rslt);

  // 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>";
  }else{
    // begin to show results set
    echo "<p>Results</p>";
    $count = 1 + $s ;
  
    while ($row = mysql_fetch_array($rslt)) {
      $link = $row['ResLink'];
      $link_title = $row['ResName'];
   
      echo $count . '.) <a href="' . $link . '">' . $link_title . '</a><br />';
      $count++;
    }
   
    $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 " <a href=\"?s={$prevs}&".http_build_query($get)."\"><< Prev 10</a>&nbsp ";
    }
   
    // calculate number of pages needing links
    $pages=ceil($numrows/$limit);

    // check to see if last page
    if($s + $limit < $numrows){
      // not last page so give NEXT link
      $next = $s + $limit;
      print " <a href=\"?s={$next}&".http_build_query($get)."\">Next 10 >></a>";
    }

    $a = $s + $limit;
    if($a > $numrows)
      $a = $numrows;
    echo "<p>Showing results ".($s + 1)." to {$a} of {$numrows}</p>";
  }
?>

Thank you so much for all your help :D

 

Its works, but of course there is another problem now.

 

when i type in a restaurant name like 'fish frenzy'  and just search that its fine but if i add 'fish frenzy hobart' it lists all the restaurants in hobart as well as fish frenzy where is should list fish frenzy hobart only kind of thing.

 

Is it a big  job to make it do that? i am sorry to ask so many questions its just i really have no idea. :D thanks again for helping me with teh code :D

 

 

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.