I have also added a search bar to my site on every page. I did have help with this from two 3rd year students Claire Anthony and Liam Smith who helped me create the tables in php MyAdmin and helped with the coding. I also had help from Dave Carr who helped me sort out the CSS for the search bar. So now if you type in running in the search bar it will take you to a search.php page where the results are shown.
PHP Code
I created a table in my sites database in phpMyAdmin called searchbarpages. In this table I created 8 fields for the 8 pages on my site. From the instructions I had been given from Claire Anthony I added pageID, pagename, pageurl and content into each field. So the index/home page looked like the screenshot below with 1, home and url and content for that page in the value boxes.

I then had help adding the code to my site so I could retrieve the information for the search bar. I added the following code to the top of each page of my site in Dreamweaver
//ob_start();
session_start();
// db properties
include ("inc/_search.php");
define('DBHOST','localhost');
define('DBUSER','username goes here');
define('DBPASS','database password goes here);
define('DBNAME','database name goes
here');
// make a connection to mysql here
$conn = @mysql_connect (DBHOST, DBUSER, DBPASS);
$conn = @mysql_select_db (DBNAME);
if(!$conn){
die( "Sorry! There seems to be a problem connecting to our database.");
}
?>
I then created a page called search.php whe
re the results from each search would be displayed again I had help from Liam Smith and Dave Carr with this. Below is the code I added on the search.php page in Dreamweaver so the results displayed.
//get search results from database
//******************replace tablename with name of table in database. Replace fieldname and otherfieldname with columns in table that you want to search
if($srch_ck){
if(empty($srch)){
echo "No search";
}else{
echo "
Showing search results for '".$srch."'
"; $sql = "SELECT * FROM searchbarpages where pagename LIKE '%".$srch."%' OR content LIKE '%".$srch."%' ORDER BY pagename ASC";
$result = mysql_query($sql)or die ('I cannot because: ' . mysql_error());
$num_rows = mysql_num_rows($result);
if($num_rows == 0){
echo "No results";
}else{
//echo "There was". $num_rows ."results";
while($row = mysql_fetch_object($result))
{
//*****************************replace with fields that you want to pull from database
$pageID = $row->pageID;
$pagename= $row->pagename;
$pageurl= $row->pageurl;
$content= $row->content;
echo $pagename.'
';
';
echo $content.'
';
';
//creates a link to the page
}
}
}
}
?>
Below are screenshots of the search bar on the index/home page and the search.php page


No comments:
Post a Comment