My question is rather lengthy, so I'll get right to it. I have a search engine set up that sends data (GET method) to a php script which queries a MySQL database and then displays the results. You can view the project, to get a better understanding, here: http://www.quinterest.org/testcategory/
The form consist of a search box as well as a multiple select option that narrow the search.
Everything thing works wonderfully, but there is one thing I would like to change and I don't know how. If someone could explain, in detail, what I need to do to be able to show the results (I figure it will be in a div written in the HTML?) from the query on the same page as the original form without the need to refresh the page?
If you would like an example, here is one: http://quizbowldb.com/search
The search stays on the same page.
P.S. I know the mysql_ functions are outdated. Please don't harass me. I'm all very new to this still and the mysql_ functions are simple, easy and good enough for what I need. When I get further programming experience (I'm still in middle school), I may convert it to PDO or MySQLi.
HTML Form:
<form action='search.php' method='GET' class="form-search">
<input type='text' placeholder="What would you like to learn about?" class="input-xxlarge search-query" id="inputInfo" name='search'><br></br>
<input type='submit' class="btn btn-large btn-primary" name='submit' value='Search'></br>
<select multiple="multiple" name='category[]'>
<option value="%">All</option>
<option>Literature</option>
<option>History</option>
<option>Science</option>
<option>Fine Arts</option>
<option>Trash</option>
<option>Mythology</option>
<option>Phylosophy</option>
<option>Social Science</option>
<option>Religion</option>
<option>Geography</option>
</select>
</center>
</form>
search.php
<?php
$button = $_GET ['submit'];
$search = $_GET ['search'];
print $search;
//validating search term length and connecting to db
if(strlen($search)<=1)
echo "Search term too short";
else{
echo "You searched for <b><em>$search</em></b> and ";
mysql_connect("fake","fake","fake");
mysql_select_db("quinterestdb");}
//validating search term for protection; if statement to avoid errors being displayed
if (strlen($search)>1){
mysql_real_escape_string($search);}
//exploding search with multiple words
$search_exploded = explode (" ", $search); //creates array of all terms in search
foreach($search_exploded as $search_each) //loops through array
{
$x++;
if($x==1)
$construct .="Answer LIKE '%$search_each%'"; //if only one value in array
else
$construct .="AND Answer LIKE '%$search_each%'"; //for each multiple value in array
}
$cat = $_GET ['category']; //preparing array (multiple choices)
if (is_array($cat))
{
foreach($cat as $val) //
{
if($val=="%") //if no category is selected
continue;
else //split array choices (separated by ' and ,)
$comma_separated = implode("','", $cat);
$newvar = "AND Category IN('$comma_separated')"; //if category is chosen
}
} //ignore for now
$constructs ="SELECT * FROM tossupsdb WHERE $construct $newvar"; //completed search query
//quering the database; if statement to avoid errors being displayed
if (strlen($search)>1){
$run = mysql_query($constructs);}
print "$constructs"; //ignore for now
//number of results found; if statement to avoid errors being displayed
if (strlen($search)>1){
$foundnum = mysql_num_rows($run);}
if ($foundnum==0)
echo "Sorry, there are no matching result for <b>$search</b>.</br></br>1.
Try more general words. for example: If you want to search 'how to create a website'
then use general keyword like 'create' 'website'</br>2. Try different words with similar
meaning</br>3. Please check your spelling";
else
{
echo " <span class='badge badge-info'> $foundnum </span> results were found:<hr size='5'>";
$per_page = 25; //preparing for pagination; results that appear per page
$start = $_POST['start']; //where to start results on page
$max_pages = ceil($foundnum / $per_page); //number of pages there will be
if(!$start) //starting at 0
$start=0;
$getquery = mysql_query("SELECT * FROM tossupsdb WHERE $construct $newvar LIMIT $start, $per_page");
while($runrows = mysql_fetch_array($getquery)) //fetching results
{
$answer = $runrows ['Answer']; //obtaining individual data from database
$category = $runrows ['Category']; //obtaining individual data from database
$num = $runrows ['Question #']; //obtaining individual data from database
$difficulty = $runrows ['Difficulty']; //obtaining individual data from database
$question = $runrows ['Question']; //obtaining individual data from database
$round = $runrows ['Round']; //obtaining individual data from database
$tournament = $runrows ['Tournament']; //obtaining individual data from database
$year = $runrows ['Year']; //obtaining individual data from database
//what will be displayed on the results page
echo "<div class='alert alert-info' style='border-radius: 20px'><div style='padding: 10px'>
<span class='label label-info' font-size='30px'><em>Tournament | Year | Round | Question # | Category</em></span></div>
<b>$tournament |</b> <b>$year |</b> <b>$round |</b> <b>$num |</b> <b>$category</b>
<p><em>Question:</em> $question</p>
<div class='alert alert-info'><em><strong>ANSWER:</strong></em> $answer</div></div><hr>
";
}
//Pagination Starts
echo "<center>";
$prev = $start - $per_page;
$next = $start + $per_page;
$adjacents = 3;
$last = $max_pages - 1;
if($max_pages > 1)
{
//previous button
if (!($start<=0))
echo " <a class='btn btn-primary btn-large' href='search.php?search=$search&submit=Search+source+code&start=$prev'>Prev</a> ";
//pages
if ($max_pages < 7 + ($adjacents * 2)) //not enough pages to bother breaking it up
{
$i = 0;
for ($counter = 1; $counter <= $max_pages; $counter++)
{
if ($i == $start){
echo " <a class='btn' href='search.php?search=$search&submit=Search+source+code&start=$i'><b>$counter</b></a> ";
}
else {
echo " <a class='btn' href='search.php?search=$search&submit=Search+source+code&start=$i'>$counter</a> ";
}
$i = $i + $per_page;
}
}
elseif($max_pages > 5 + ($adjacents * 2)) //enough pages to hide some
{
//close to beginning; only hide later pages
if(($start/$per_page) < 1 + ($adjacents * 2))
{
$i = 0;
for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++)
{
if ($i == $start){
echo " <a class='btn' href='search.php?search=$search&submit=Search+source+code&start=$i'><b>$counter</b></a> ";
}
else {
echo " <a class='btn' href='search.php?search=$search&submit=Search+source+code&start=$i'>$counter</a> ";
}
$i = $i + $per_page;
}
}
//in middle; hide some front and some back
elseif($max_pages - ($adjacents * 2) > ($start / $per_page) && ($start / $per_page) > ($adjacents * 2))
{
echo " <a class='btn' href='search.php?search=$search&submit=Search+source+code&start=0'>1</a> ";
echo " <a class='btn' href='search.php?search=$search&submit=Search+source+code&start=$per_page'>2</a> .... ";
$i = $start;
for ($counter = ($start/$per_page)+1; $counter < ($start / $per_page) + $adjacents + 2; $counter++)
{
if ($i == $start){
echo " <a class='btn' href='search.php?search=$search&submit=Search+source+code&start=$i'><b>$counter</b></a> ";
}
else {
echo " <a class='btn' href='search.php?search=$search&submit=Search+source+code&start=$i'>$counter</a> ";
}
$i = $i + $per_page;
}
}
//close to end; only hide early pages
else
{
echo " <a class='btn' href='search.php?search=$search&submit=Search+source+code&start=0'>1</a> ";
echo " <a class='btn' href='search.php?search=$search&submit=Search+source+code&start=$per_page'>2</a> .... ";
$i = $start;
for ($counter = ($start / $per_page) + 1; $counter <= $max_pages; $counter++)
{
if ($i == $start){
echo " <a class='btn' href='search.php?search=$search&submit=Search+source+code&start=$i'><b>$counter</b></a> ";
}
else {
echo " <a class='btn' href='search.php?search=$search&submit=Search+source+code&start=$i'>$counter</a> ";
}
$i = $i + $per_page;
}
}
}
//next button
if (!($start >=$foundnum-$per_page))
echo " <a class='btn btn-primary btn-large' href='search.php?search=$search&submit=Search+source+code&start=$next'>Next</a> ";
}
echo "</center>";
}
?>
You need to use AJAX to do that. Using AJAX, you send asynchronous requests (requests without loading the page) to the server.
This is how Google and other major search engines work. Learn about it here : Ajax tutorial
Ajax - Asynchronous JavaScript And XML
From Wikipedia definition of Ajax:
With Ajax, web applications can send data to, and retrieve data from, a server asynchronously (in the background) without interfering with the display and behavior of the existing page.
Data can be retrieved using the XMLHttpRequest object.
Despite the name, the use of XML is not required (JSON is often used instead), and the requests do not need to be asynchronous.
The simplest way to accomplish this is probably via jQuery, a JavaScript framework; by "simple", I mean the least work on your end:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
// This is the equivalent of the older $(document).ready() event
$(function(){
$('#search-form').on('submit', function(event){
event.preventDefault(); // prevents form submission
var data = $('#search-form').serialize(); // get all of the input variables in a neat little package
var action = $('#search-form').attr('action'); // get the page to get/post to
$.get(action, data, function(response, status, jqxhr){
$('#target').html(response);
});
});
});
</script>
Here, I add an id to your form so that I can directly target it. I also assume that there is a HTML element with an id of target that I can inject with the response HTML (which I also assume is only a fragment).
Related
I have a search result with pagination that I make using this http://www.findsourcecode.com/php/pagination-in-search-engine/ as a reference. The website is using mysql and GET method for search. I change mysql to mysqli and work well. Then, I try to change the Get method to Post method for search result. The Post method is more secure based on what I readed. The question is how to change the method and make it work? The problem I face is, the result do not show at the second page but the first page show the result like I wanted. Please Helpp!!
Below is my coding..
index.php(the search form)
<div class="container">
<img src="image/sbback.jpg">
<div class="center">
<form class="form-wrapper cf" action="page.php" method="POST">
<input type="text" placeholder="Search here..." name="search" required>
<button type="submit" name="submit" value="Search source code" ><img src="image/search1.png" width="30" height="30" vspace="11"></button>
</form>
</div>
</div>
page.php
<?php
include( 'session.php' );
header('Cache-Control: no cache'); //no cache
if(isset($_SESSION['user']['role'])){
$role=$_SESSION['user']['role'];
}
?>
<?php
if (isset($_POST['submit'])){
$search = mysqli_real_escape_string($connection, $_POST['search']);
if(strlen($search)<=1)
echo "Search term too short";
else{
echo "You searched for <b>$search</b> <hr size='1'></br>";
$connection=mysqli_connect("localhost","root","","company");
$search_exploded = explode (" ", $search);
$x = "";
$construct = "";
foreach($search_exploded as $search_each)
{
$x++;
if($x==1)
$construct .="title LIKE '%$search_each%' OR description LIKE '%$search_each%' OR author LIKE '%$search_each%' OR date LIKE '%$search_each%' OR time LIKE '%$search_each%'";
else
$construct .="AND title LIKE '%$search_each%' OR description LIKE '%$search_each%' OR author LIKE '%$search_each%' OR date LIKE '%$search_each%' OR time LIKE '%$search_each%'";
}
$constructs ="SELECT * FROM tbl_uploads WHERE $construct";
$run = mysqli_query($connection,$constructs);
$foundnum = mysqli_num_rows($run);
if ($foundnum==0)
echo "Sorry, there are no matching result for <b>$search</b>.</br></br>1.
Try more general words. for example: If you want to search 'how to create a website'
then use general keyword like 'create' 'website'</br>2. Try different words with similar
meaning</br>3. Please check your spelling";
else
{
echo "$foundnum results found !<p>";
$per_page = 10;
$start = isset($_GET['start']) ? $_GET['start']: '';
$max_pages = ceil($foundnum / $per_page);
if(!$start)
$start=0;
$sql = "SELECT * FROM tbl_uploads WHERE $construct LIMIT $start,$per_page";
$getquery = mysqli_query($connection,$sql);
while($runrows = mysqli_fetch_assoc($getquery))
{
$title = $runrows ['title'];
$desc = $runrows ['description'];
$author = $runrows ['author'];
$date = $runrows ['date'];
$time = $runrows ['time'];
echo '<a href="uploads/'.$runrows['file'].'">
'.$runrows['title'].'</a>
<p>'.$desc.'</p>
<p>'.$author.' / '.$date.' / '.$time.'</p>';
}
//Pagination Starts
echo "<center>";
$prev = $start - $per_page;
$next = $start + $per_page;
$adjacents = 3;
$last = $max_pages - 1;
if($max_pages > 1)
{
//previous button
if (!($start<=0))
echo " <a href='page.php?search=$search&submit=Search+source+code&start=$prev'>Prev</a> ";
//pages
if ($max_pages < 7 + ($adjacents * 2)) //not enough pages to bother breaking it up
{
$i = 0;
for ($counter = 1; $counter <= $max_pages; $counter++)
{
if ($i == $start){
echo " <a href='page.php?search=$search&submit=Search+source+code&start=$i'><b>$counter</b></a> ";
}
else {
echo " <a href='page.php?search=$search&submit=Search+source+code&start=$i'>$counter</a> ";
}
$i = $i + $per_page;
}
}
elseif($max_pages > 5 + ($adjacents * 2)) //enough pages to hide some
{
//close to beginning; only hide later pages
if(($start/$per_page) < 1 + ($adjacents * 2))
{
$i = 0;
for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++)
{
if ($i == $start){
echo " <a href='page.php?search=$search&submit=Search+source+code&start=$i'><b>$counter</b></a> ";
}
else {
echo " <a href='page.php?search=$search&submit=Search+source+code&start=$i'>$counter</a> ";
}
$i = $i + $per_page;
}
}
//in middle; hide some front and some back
elseif($max_pages - ($adjacents * 2) > ($start / $per_page) && ($start / $per_page) > ($adjacents * 2))
{
echo " <a href='page.php?search=$search&submit=Search+source+code&start=0'>1</a> ";
echo " <a href='search.php?search=$search&submit=Search+source+code&start=$per_page'>2</a> .... ";
$i = $start;
for ($counter = ($start/$per_page)+1; $counter < ($start / $per_page) + $adjacents + 2; $counter++)
{
if ($i == $start){
echo " <a href='page.php?search=$search&submit=Search+source+code&start=$i'><b>$counter</b></a> ";
}
else {
echo " <a href='page.php?search=$search&submit=Search+source+code&start=$i'>$counter</a> ";
}
$i = $i + $per_page;
}
}
//close to end; only hide early pages
else
{
echo " <a href='page.php?search=$search&submit=Search+source+code&start=0'>1</a> ";
echo " <a href='search.php?search=$search&submit=Search+source+code&start=$per_page'>2</a> .... ";
$i = $start;
for ($counter = ($start / $per_page) + 1; $counter <= $max_pages; $counter++)
{
if ($i == $start){
echo " <a href='page.php?search=$search&submit=Search+source+code&start=$i'><b>$counter</b></a> ";
}
else {
echo " <a href='page.php?search=$search&submit=Search+source+code&start=$i'>$counter</a> ";
}
$i = $i + $per_page;
}
}
}
//next button
if (!($start >=$foundnum-$per_page))
echo " <a href='page.php?search=$search&submit=Search+source+code&start=$next'>Next</a> ";
}
echo "</center>";
}
}
}
?>
Hi I have here a code which will search for a name then returns the result paginated. I'm having an error on lines 19 and 20 which is
Notice: Undefined index: submit in C:\xampp\htdocs\eventreg\trypaginate2.php on line 19 - NOW OK
and
Notice: Undefined index: search in C:\xampp\htdocs\eventreg\trypaginate2.php on line 20 - NOW OK
But it is working. When I turn to the next page it won't show any results just a blank page.
Here is my html code:
<html>
<head>
<title>Title of your search engine</title>
</head>
<body>
<form action='trypaginate2.php' method='POST'>
<center>
<h1>My Search Engine</h1>
<input type='text' size='90' name='search'></br></br>
<input type='submit' name='submit' value='Search source code' ></br></br></br>
</center>
</form>
</body>
</html>
Then php code here:
<?php
if(array_key_exists('search', $_GET))
{
echo "hello";
$search = $_GET['search'];
echo "$search";
}
if(isset($_POST['submit']))
{
if(array_key_exists('search', $_POST))
{
echo "hi";
$search = $_POST['search'];
}
}
if(strlen($search)<=1)
echo "Search term too short";
else
{
echo "You searched for <b>$search</b> <hr size='1'></br>";
include("dbcon.php");
$search_exploded = explode (" ", $search);
$x = "";
$construct = "";
foreach($search_exploded as $search_each)
{
$x++;
if($x==1)
$construct .="name LIKE '%$search_each%'";
else
$construct .="AND name LIKE '%$search_each%'";
}
echo $construct;
$constructs ="SELECT * FROM reginformation WHERE $construct";
$run = mysql_query($constructs);
$foundnum = mysql_num_rows($run);
if ($foundnum==0)
echo "Sorry, there are no matching result for <b>$search</b>.</br></br>1.
Try more general words. for example: If you want to search 'how to create a website'
then use general keyword like 'create' 'website'</br>2. Try different words with similar
meaning</br>3. Please check your spelling";
else
{
echo "$foundnum results found !<p>";
$per_page = 5;
$start = isset($_GET['start']) ? $_GET['start']: '';
$max_pages = ceil($foundnum / $per_page);
if(!$start)
$start=0;
$getquery = mysql_query("SELECT * FROM reginformation WHERE $construct LIMIT $start, $per_page");
/*while($runrows = mysql_fetch_assoc($getquery))
{
$title = $runrows ['regID'];
$desc = $runrows ['name'];
$url = $runrows ['address'];
echo "
<a href='$url'><b>$title</b></a><br>
$desc<br>
<a href='$url'>$url</a><p>
";
}*/
if(mysql_num_rows($getquery)>0)
{
while ($row = mysql_fetch_assoc($getquery)) {
// echo data
echo "<tr onClick =window.location='infodetailsresp.php?id=$row[regID]'><td>$row[name]</td><td>$row[emailadd]</td><td>$row[contactno]</td><td>$row[event]</td><td>$row[date_register]</td></tr><br>";
} // end while
}
else
{
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('No record found.');
window.location.href='reglistresp.php';
</SCRIPT>");
}
//Pagination Starts
echo "<center>";
$prev = $start - $per_page;
$next = $start + $per_page;
$adjacents = 3;
$last = $max_pages - 1;
if($max_pages > 1)
{
//previous button
if (!($start<=0))
echo " <a href='trypaginate2.php?search=$search&submit=Search+source+code&start=$prev'>Prev</a> ";
//pages
if ($max_pages < 7 + ($adjacents * 2)) //not enough pages to bother breaking it up
{
$i = 0;
for ($counter = 1; $counter <= $max_pages; $counter++)
{
if ($i == $start)
{
echo " <a href='trypaginate2.php?search=$search&submit=Search+source+code&start=$i'><b>$counter</b></a> ";
}
else
{
echo " <a href='trypaginate2.php?search=$search&submit=Search+source+code&start=$i'>$counter</a> ";
}
$i = $i + $per_page;
}
}
elseif($max_pages > 5 + ($adjacents * 2)) //enough pages to hide some
{
//close to beginning; only hide later pages
if(($start/$per_page) < 1 + ($adjacents * 2))
{
$i = 0;
for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++)
{
if ($i == $start)
{
echo " <a href='trypaginate2.php?search=$search&submit=Search+source+code&start=$i'><b>$counter</b></a> ";
}
else
{
echo " <a href='trypaginate2.php?search=$search&submit=Search+source+code&start=$i'>$counter</a> ";
}
$i = $i + $per_page;
}
}
//in middle; hide some front and some back
elseif($max_pages - ($adjacents * 2) > ($start / $per_page) && ($start / $per_page) > ($adjacents * 2))
{
echo " <a href='trypaginate2.php?search=$search&submit=Search+source+code&start=0'>1</a> ";
echo " <a href='trypaginate2.php?search=$search&submit=Search+source+code&start=$per_page'>2</a> .... ";
$i = $start;
for ($counter = ($start/$per_page)+1; $counter < ($start / $per_page) + $adjacents + 2; $counter++)
{
if ($i == $start)
{
echo " <a href='trypaginate2.php?search=$search&submit=Search+source+code&start=$i'><b>$counter</b></a> ";
}
else
{
echo " <a href='trypaginate2.php?search=$search&submit=Search+source+code&start=$i'>$counter</a> ";
}
$i = $i + $per_page;
}
}
//close to end; only hide early pages
else
{
echo " <a href='trypaginate2.php?search=$search&submit=Search+source+code&start=0'>1</a> ";
echo " <a href='trypaginate2.php?search=$search&submit=Search+source+code&start=$per_page'>2</a> .... ";
$i = $start;
for ($counter = ($start / $per_page) + 1; $counter <= $max_pages; $counter++)
{
if ($i == $start)
{
echo " <a href='trypaginate2.php?search=$search&submit=Search+source+code&start=$i'><b>$counter</b></a> ";
}
else
{
echo " <a href='trypaginate2.php?search=$search&submit=Search+source+code&start=$i'>$counter</a> ";
}
$i = $i + $per_page;
}
}
}
//next button
if (!($start >=$foundnum-$per_page))
echo " <a href='trypaginate2.php?search=$search&submit=Search+source+code&start=$next'>Next</a> ";
}
echo "</center>";
}
}
?>
EDIT! Changed my php code now I'm getting an error on line 34. The error is Notice: Undefined variable: search in C:\xampp\htdocs\eventreg\trypaginate2.php on line 34
You shouldn't check whether a key exists in array (which is what $_POST and $_GET are) by blindly assigning variables to those values or even by using isset - even though I know that seems like it would make sense. That's the behavior that PHP is sending you a warning about. That error comes from trying to find the value of things like $_POST['search'] or $_GET['submit'] when those values aren't set in that array.
Instead, use array_key_exists('submit', $_GET) or array_key_exists('search', $_POST) to check whether those values are set. If that expression evaluates to true, then you can proceed with accessing those values in your code and you should not receive any notices in the logs.
i can make pagination by query database and it works just fine. but when i use form to search from database, i can only get the first page data, the next page data won't show up.
i just cannot figure out how to maintain the search query..
this is my code. the problem should be in the url links in the pagination, but i just cannot see the problem
<?php
require('koneksi.php');
if(isset($_GET['search'])) {
$search = $_GET['search'];
$keyword = $_GET['keyword'];
$koneksi = mysqli_connect("localhost","root","","mycompany");
// find out how many rows are in the table
$sql = "SELECT COUNT(*) FROM product WHERE deskripsi LIKE '%" . $keyword . "%'";
$result = mysqli_query($koneksi,$sql);
$rss = mysqli_fetch_row($result);
$numrows = $rss[0];
//numbers or rows to show per page
$rowperpage = 6;
//find out total pages
$totalpages = ceil($numrows/$rowperpage);
//get the current page or set default
if(isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) {
// cast var as int
$currentpage = (int) $_GET['currentpage'];
} else {
// default page number
$currentpage = 1;
} // end if
// if the current page is greater than total pages...
if($currentpage > $totalpages) {
// set current page to last page
$currentpage = $totalpages;
} // end if
// if current page is less than total pages...
if($currentpage < 1) {
// set current page to first page
$currentpage = 1;
} // end if
// the offset of the list, based on current page
$offset = ($currentpage - 1) * $rowperpage;
$sql = "SELECT * FROM product WHERE deskripsi LIKE '%" . $keyword . "%' LIMIT $offset, $rowperpage";
$result = mysqli_query($koneksi, $sql);
// while there are rows to be fetched
while ($list = mysqli_fetch_assoc($result)) {
// echo data
echo $list['product_code'];
echo "<br>";
echo $list['deskripsi'];
}
/****** build the pagination links ******/
// range of num links to show
$range = 6;
$url = "searchbar.php";
// if not on page 1, don't show back links
if($currentpage > 1) {
// show << link to go to page 1
echo "<a href='{$_SERVER['PHP_SELF']}?currentpage=1'> << </a>";
//get previous page num
$prevpage = $currentpage - 1;
} // end if
echo " <li class='arrow'><a href='$url?currentpage=prevpage?&keyword=$keyword?cari=$cari'>«</a></li> ";
for($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) {
// if it is a valid page number
if(($x > 0) && ($x <= $totalpages)) {
// if we are on current page
if($x == $currentpage) {
echo "<li class=''><a href=''> $x </a></li>";
} else {
// make it a link
//echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$x'> $x </a> ";
//echo "<li class=''><a href='{$_SERVER['PHP_SELF']}?currentpage=$x'>$x </a></li>";
echo "<li class=''><a href='$url?currentpage=$x?&keyword=$keyword?cari=$cari'> $x </a></li>";
} // end else
} // end if
} // end for
// if not on last page, show forward and last page links
if ($currentpage != $totalpages) {
// get next page
$nextpage = $currentpage + 1;
// echo forward link for next page
echo " <li class='arrow'><a href='$url?currentpage=$nextpage?&keyword=$keyword?cari=$cari'>»</a></li> ";
// echo forward link for lastpage
// echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$totalpages'> >> </a> ";
} // end if
} // end if get search
require('footer.php');
?>
Looks like there could be a couple things missing here. For instance:
echo " <li class='arrow'><a href='$url?currentpage=prevpage?&keyword=$keyword?cari=$cari'>«</a></li> ";
in this line you are missing a $ for the prevpage: $prevpage but the querystring in the URL should only start with a ? and not contain question marks elsewhere, so this line should read more like
echo " <li class='arrow'><a href='$url?currentpage=$prevpage&keyword=$keyword&cari=$cari'>«</a></li> ";
I'm not 100% sure if that's going to fix your issue, but there is one big thing that I would ask you to look into before actually using this code anywhere and that's the SQL Injection that you have in your query.
You might read a bit of How can I prevent SQL injection in PHP? to get a better idea of how to rewrite your sql queries.
So, checkout your links, make sure the querystring is formatted correctly (http://host.com/script.php?querystring=something&var2=anothervar) where variables are separated only by &
As #aaronott pointed out, most of your links are wrong.
You are using cari=$cari which is not set anywhere, while in fact I guess you should add search=1 (or search=$search, but it's not really useful).
Also, you cannot have more than on ? in your querystring, so fix all your links like this:
...
if($currentpage > 1) {
echo "<a href='{$_SERVER['PHP_SELF']}?currentpage=1&search=1&keyword=$keyword'> << </a>";
$prevpage = $currentpage - 1;
}
echo " <li class='arrow'><a href='$url?currentpage=$prevpage&search=1&keyword=$keyword'>«</a></li> ";
...
if($x == $currentpage) {
echo "<li class=''><a href=''> $x </a></li>";
} else {
echo "<li class=''><a href='$url?currentpage=$x&search=1&keyword=$keyword'> $x </a></li>";
} // end else
...
echo " <li class='arrow'><a href='$url?currentpage=$nextpage&search=1&keyword=$keyword'>»</a></li> ";
may I ask how can I add an autocomplete for my simple search engine.
Below is the Index.php
<html>
<head>
<title>Title of your search engine</title>
</head>
<body>
<form action='search.php' method='GET'>
<center>
<h1>My Search Engine</h1>
<input type='text' size='90' name='search'></br></br>
<input type='submit' name='submit' value='Search source code' ></br></br></br>
</center>
</form>
</body>
</html>
And here's the search.php
<?php
$button = $_GET ['submit'];
$search = $_GET ['search'];
if(strlen($search)<=1)
echo "Search term too short";
else{
echo "You searched for <b>$search</b> <hr size='1'></br>";
$m_Host = "localhost";
$m_User = "root";
$m_Pass = "Kyrene";
$m_Db = "ensemble";
$connect = mysql_connect($m_Host,$m_User,$m_Pass) or die(mysql_error());
echo "<br />";
mysql_select_db($m_Db,$connect) or die(mysql_error());
error_reporting(error_reporting()&~E_NOTICE);
$search_exploded = explode (" ", $search);
foreach($search_exploded as $search_each)
{
$x++;
if($x==1)
$construct .="title LIKE '%$search_each%'";
else
$construct .="AND title LIKE '%$search_each%'";
}
$constructs ="SELECT * FROM test WHERE $construct";
$run = mysql_query($constructs);
$foundnum = mysql_num_rows($run);
if ($foundnum==0)
echo "Sorry, there are no matching result for <b>$search</b>.</br></br>1.
Try more general words. for example: If you want to search 'how to create a website'
then use general keyword like 'create' 'website'</br>2. Try different words with similar
meaning</br>3. Please check your spelling";
else
{
echo "$foundnum results found !<p>";
$per_page = 1;
$start = $_GET['start'];
$max_pages = ceil($foundnum / $per_page);
if(!$start)
$start=0;
$getquery = mysql_query("SELECT * FROM test WHERE $construct LIMIT $start, $per_page");
while($runrows = mysql_fetch_assoc($getquery))
{
$title = $runrows ['title'];
$desc = $runrows ['description'];
$url = $runrows ['url'];
echo "
<a href='$url'><b>$title</b></a><br>
$desc<br>
<a href='$url'>$url</a><p>
";
}
//Pagination Starts
echo "<center>";
$prev = $start - $per_page;
$next = $start + $per_page;
$adjacents = 3;
$last = $max_pages - 1;
if($max_pages > 1)
{
//previous button
if (!($start<=0))
echo " <a href='search.php?search=$search&submit=Search+source+code&start=$prev'>Prev</a> ";
//pages
if ($max_pages < 7 + ($adjacents * 2)) //not enough pages to bother breaking it up
{
$i = 0;
for ($counter = 1; $counter <= $max_pages; $counter++)
{
if ($i == $start){
echo " <a href='search.php?search=$search&submit=Search+source+code&start=$i'><b>$counter</b></a> ";
}
else {
echo " <a href='search.php?search=$search&submit=Search+source+code&start=$i'>$counter</a> ";
}
$i = $i + $per_page;
}
}
elseif($max_pages > 5 + ($adjacents * 2)) //enough pages to hide some
{
//close to beginning; only hide later pages
if(($start/$per_page) < 1 + ($adjacents * 2))
{
$i = 0;
for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++)
{
if ($i == $start){
echo " <a href='search.php?search=$search&submit=Search+source+code&start=$i'><b>$counter</b></a> ";
}
else {
echo " <a href='search.php?search=$search&submit=Search+source+code&start=$i'>$counter</a> ";
}
$i = $i + $per_page;
}
}
//in middle; hide some front and some back
elseif($max_pages - ($adjacents * 2) > ($start / $per_page) && ($start / $per_page) > ($adjacents * 2))
{
echo " <a href='search.php?search=$search&submit=Search+source+code&start=0'>1</a> ";
echo " <a href='search.php?search=$search&submit=Search+source+code&start=$per_page'>2</a> .... ";
$i = $start;
for ($counter = ($start/$per_page)+1; $counter < ($start / $per_page) + $adjacents + 2; $counter++)
{
if ($i == $start){
echo " <a href='search.php?search=$search&submit=Search+source+code&start=$i'><b>$counter</b></a> ";
}
else {
echo " <a href='search.php?search=$search&submit=Search+source+code&start=$i'>$counter</a> ";
}
$i = $i + $per_page;
}
}
//close to end; only hide early pages
else
{
echo " <a href='search.php?search=$search&submit=Search+source+code&start=0'>1</a> ";
echo " <a href='search.php?search=$search&submit=Search+source+code&start=$per_page'>2</a> .... ";
$i = $start;
for ($counter = ($start / $per_page) + 1; $counter <= $max_pages; $counter++)
{
if ($i == $start){
echo " <a href='search.php?search=$search&submit=Search+source+code&start=$i'><b>$counter</b></a> ";
}
else {
echo " <a href='search.php?search=$search&submit=Search+source+code&start=$i'>$counter</a> ";
}
$i = $i + $per_page;
}
}
}
//next button
if (!($start >=$foundnum-$per_page))
echo " <a href='search.php?search=$search&submit=Search+source+code&start=$next'>Next</a> ";
}
echo "</center>";
}
}
?>
I don't really have idea how should i start it. Any help is greatly appreciated. Thanks!
I will give you the general shpill of how to do it. 1. Use ajax to fetch data. 2. present data. if you are using jQuery
$("#search").autocomplete(
{
source : function(request, response) {
$.ajax({
type : 'get',
url : "http://hostname.com/suggest.php",
data : {
search : document.getElementById("search").value
},
success : function(result) {
response(result.list);
},
dataType : 'json',
global : false
});
}
});
in your suggest.php
<?php
$str = $_GET['search'];
//query database, get results
echo json_encode(array('list'=>$mydata));
?>
and the id='search' to your search input tag
I am building a product catalog, that I want to be determined depending on users device. ie., if windows device show particular products. I have my products listing absolutely fine, however when implementing pagination, I am stuck.
I want only 6 items to be listed per page, I have more results. However more results are showing on the first page. When I select to go next, the ID number changes, to show it is showing me the next result, but it continues to show the same page, so obviously I am missing/got confused somewhere with my code. I'd appreciate any advice:
$current_url = $_SERVER['REQUEST_URI'];
$current_url = substr($current_url, 1);
$results = mysqli_query($conn, "SELECT * FROM apps A INNER JOIN device D ON D.DeviceID = A.DeviceID WHERE D.DeviceName = '$os'");
$foundnum = mysqli_num_rows($results);
if ($foundnum==0){
echo "Sorry, there are currently no applications that are compatible with your device. Please try another option.";
} else {
echo "$foundnum applications are avaliable for '$os' devices:<p>";
$per_page = 6;
$start = $_GET['start'];
$max_pages = ceil($foundnum / $per_page);
if(!$start)
$start=0;
while($obj = $results->fetch_object()){
$applicationid=$obj->ApplicationID;
$start=0;
echo "<div class=\"col-4 col-sm-4 col-lg-4\">";
echo '<form method="post" action="cart_update.php">';
echo "<div id='product'><a href='appproduct.php?id=$applicationid'><img src='images/app_images/$applicationid.jpg' alt='Product picture'/></div>";
echo '<h2>'.$obj->ApplicationName.'</h2>';
echo '<p>'.$obj->ApplicationDescription.'</p>';
if($obj->App_cost=="0.00"){
echo '<p>Free</p>';
}else{
echo '<p>£'.$obj->App_cost.'</p>';
}
echo '<button class="add_to_cart">Add To Cart</button>';
echo '<input type="hidden" name="product_code" value="'.$obj->ApplicationID.'" />';
echo '<input type="hidden" name="type" value="add" />';
echo '<input type="hidden" name="return_url" value="'.$current_url.'" />';
echo '</form><br /><br /></div>';
}
//Pagination Starts
echo "<center>";
$prev = $start - $per_page;
$next = $start + $per_page;
$last = $max_pages - 1;
if($max_pages > 1){
//previous button
if (!($start<=0))
echo "<a href='index.php?os=$os=Search+source+code&start=$prev'>Prev |</a> ";
//pages
$i = 0;
for ($counter = 1; $counter <= $max_pages; $counter++){
if($i == $start){
echo " <a href='index.php?os=$os=Search+source+code&start=$i'><b> $counter |</b></a> ";
}
else {
echo " <a href='index.php?os=$os=Search+source+code&start=$i'> $counter |</a> ";
}
$i = $i + $per_page;
}
}
//next button
if (!($start >=$foundnum-$per_page))
echo " <a href='index.php?os=$os=Search+source+code&start=$next'> Next</a> ";
}
echo "</center>"
?>
You should try to do the pagination via database, instead of loading all the results eagerly. If you had 100000 records and wanted to show only first 6 of them, you'd need to fetch 99994 records you might not use. Try to use limit of sql.
As for your problem with "bolding" current page number, you have logic error here:
$i = 0;
for ($counter = 1; $counter <= $max_pages; $counter++) {
if($i == $start){
echo " <a href='index.php?os=$os=Search+source+code&start=$i'><b> $counter |</b></a> ";
} else {
echo " <a href='index.php?os=$os=Search+source+code&start=$i'> $counter |</a> ";
}
$i = $i + $per_page;
According to this snippet you are comparing $i to $start, where $i is always equal to 0, so it will bold anything only on first page.
You need to use LIMIT in your MySQL query to only get a page of results at a time. It will look something like LIMIT 0, 6.
change this line it will work
$results = mysqli_query($conn, "SELECT * FROM apps A INNER JOIN device D ON D.DeviceID = A.DeviceID WHERE D.DeviceName = '$os' LIMIT $_GET['start'], 6;");
but it's not the best way to do pagination or putting a variable straight from global variables. I would advise you to use at leat mysql escape string function in php