PHP & MySQL - Pagination display problems - php

For some reason my search script will only display the first set of results for the first page but when I click on the pagination link to the next page the results that are generated from the search script will not be displayed how can I correct this problem?
Here is my PHP & MySQL pagination code.
$x = '';
$construct = '';
if(isset($_POST['search'])) {
$search = $_POST['search'];
if(strlen($search) <= 2){
echo '';
} else {
$mysqli = mysqli_connect("localhost", "root", "", "sitename");
mysqli_select_db($mysqli, "sitename");
$search_explode = explode(" ", $search);
foreach($search_explode as $search_each) {
$x++;
if($x == 1){
$construct .= " article_content LIKE '%$search_each%' OR title LIKE '%$search_each%' OR summary LIKE '%$search_each%'";
} else {
$construct .= " OR article_content LIKE '%$search_each%' OR title LIKE '%$search_each%' OR summary LIKE '%$search_each%'";
}
}
$construct = "SELECT users.*, users_articles.* FROM users_articles
INNER JOIN users ON users_articles.user_id = users.user_id
WHERE $construct";
$run = mysqli_query($mysqli, $construct);
$search_term = mysqli_num_rows($run);
}
}
// Number of records to show per page:
$display = 10;
// Determine how many pages there are...
if (isset($_GET['p']) && is_numeric($_GET['p'])) { // Already been determined.
$pages = mysqli_real_escape_string($mysqli, htmlentities(strip_tags($_GET['p'])));
} else { // Need to determine.
// Count the number of records:
$records = $search_term;
// Calculate the number of pages...
if ($records > $display) { // More than 1 page.
$pages = ceil ($records/$display);
} else {
$pages = 1;
}
} // End of p IF.
// Determine where in the database to start returning results...
if (isset($_GET['s']) && is_numeric($_GET['s'])) {
$start = mysqli_real_escape_string($mysqli, htmlentities(strip_tags($_GET['s'])));
} else {
$start = 0;
}
// Make the links to other pages, if necessary.
if ($pages > 1) {
// Add some spacing and start a paragraph:
echo '<p>';
// Determine what page the script is on:
$current_page = ($start/$display) + 1;
//add this here... first will always be one
if ($current_page != 1) {
echo 'First';
}
// If it's not the first page, make a Previous button:
if ($current_page != 1) {
echo 'Previous ';
}
//create the links
for ($i = max(1, $current_page - 3); $i <= min($current_page + 3, $pages); $i ++) {
if ($i != $current_page) {
echo '' . $i . ' ';
} else {
echo '<span>' . $i . '</span> ';
}
}
// If it's not the last page, make a Next button:
if ($current_page != $pages) {
echo 'Next';
}
//add this here... Last will always be one
if ($current_page != $pages) {
echo 'Last';
}
echo '</p>'; // Close the paragraph.
} // End of links section.
Here is the part of PHP & MySQL search code.
$x = '';
$construct = '';
if(isset($_POST['search'])) {
$search = $_POST['search'];
if(strlen($search) <= 2){
echo 'Your search term is too short!';
} else {
$mysqli = mysqli_connect("localhost", "root", "", "sitename");
mysqli_select_db($mysqli, "sitename");
$search_explode = explode(" ", $search);
foreach($search_explode as $search_each) {
$x++;
if($x == 1){
$construct .= " article_content LIKE '%$search_each%' OR title LIKE '%$search_each%' OR summary LIKE '%$search_each%'";
} else {
$construct .= " OR article_content LIKE '%$search_each%' OR title LIKE '%$search_each%' OR summary LIKE '%$search_each%'";
}
}
$construct = "SELECT users.*, users_articles.* FROM users_articles
INNER JOIN users ON users_articles.user_id = users.user_id
WHERE $construct";
$construct .= " LIMIT $start, $display";
$run = mysqli_query($mysqli, $construct);
$foundnum = mysqli_num_rows($run);
if ($foundnum == 0) {
echo 'Search term is too short!</p>No results found.';
} else {
echo 'results';
}
}
}

That's a lot of code to look through, but could I hazard a guess that $_POST['search'] isn't set when you click on a pagination link, thus causing your entire second block of code not to be run?

Use Session . Below I show you an example of how to do it.
$number = $_POST['studentid'];
if (empty($number)) {
$number=$_SESSION['number'];
}
else{$number=$number ; )
//take a look
At the top of the page put - <? session_start(); ?>
Put the following just before the script for navigation (Next Page/Previous Page)
$_SESSION['number']=$number;
$_COOKIE['number'] = $number;

Related

Php search code with pagination(Using php) is not producing the navigation links because of a warning. How do i correct the error?

Am new to php programming and I have written my php code to search data from database then displays it with pagination links for easy navigation in the event that the search result will be too many. But the pagination links will not show because of the above warning. The query is not producing the Count result to make my $limit variable true thereby displaying the first page only. This is the code below, Please can you help me correct the error so that the pagination links show.
<?php
include_once("dbconnect.php");
if(isset($_GET["search"]))
{
$condition = '';
$search_query = explode(" ", $_GET["search"]);
foreach($search_query as $text)
{
$condition .= "search LIKE '%".mysqli_real_escape_string($dbconnect, $text)."%' OR ";
}
$sql = "SELECT COUNT(stockID) FROM stock WHERE search LIKE ". $condition ."GROUP BY stockID";
$query = mysqli_query($dbconnect, $sql);
$row = mysqli_fetch_row($query);
$rows = $row[0];
$page_rows = 12;
$last = ceil($rows/$page_rows);
if($last < 1){
$last = 1;
}
$pagenum = 1;
if(isset($_GET['pn'])){
$pagenum = preg_replace('#[^0-9]#', '', $_GET['pn']);
}
if ($pagenum < 1) {
$pagenum = 1;
} else if ($pagenum > $last) {
$pagenum = $last;
}
$limit = 'LIMIT ' .($pagenum - 1) * $page_rows .',' .$page_rows;
$condition = '';
$search_query = explode(" ", $_GET["search"]);
foreach($search_query as $text)
{
$condition .= "search LIKE
'%".mysqli_real_escape_string($dbconnect, $text)."%' OR ";
}
$condition = substr($condition, 0, -4);
$sql= "SELECT * FROM stock WHERE " . $condition."
ORDER BY stockID ASC $limit";
$query = mysqli_query($dbconnect, $sql);
$textline1 = "(<b>$rows</b>)";
$textline2 = "Page <b>$pagenum</b> of <b>$last</b>";
$paginationCtrls = '';
$search_query = $_GET['search'];
if($last != 1){
if ($pagenum > 1) {
$previous = $pagenum - 1;
$paginationCtrls .= '<a href="'.$_SERVER['PHP_SELF'].'?
pn='.$previous.'&search='.$search_query.'">Previous</a> ';
for($i = $pagenum-4; $i < $pagenum; $i++){
if($i > 0){
$paginationCtrls .= '<a href="'.$_SERVER['PHP_SELF'].'?
pn='.$i.'">'.$i.'</a> ';
}
}
}
$paginationCtrls .= ''.$pagenum.' ';
for($i = $pagenum+1; $i <= $last; $i++){
$paginationCtrls .= '<a href="'.$_SERVER['PHP_SELF'].'?
pn='.$i.'&search='.$search_query.'">'.$i.'</a> ';
if($i >= $pagenum+4){
break;
}
}
if ($pagenum != $last) {
$next = $pagenum + 1;
$paginationCtrls .= ' <a href="'.$_SERVER['PHP_SELF'].'?
pn='.$next.'&search='.$search_query.'">Next</a> ';
}
}
$list = '';
$lists = '';
while($row = mysqli_fetch_array($query)){
$id = $row["stockID"];
$name = $row["stockName"];
$image = $row["thumbnail"];
$description = $row["description"];
$topline = $row['topline'];
$lists .= '<div class="col-md-3" style="margin-bottom:10px;">
<div class="panel panel-info"><a href="index.php?
page=item&stockID='.$id.'&sub_category=">
<div class="panel-body">
<img class="img-responsive" style="height:100px;"
src="resources/stocks_images/'.$image.'" />
</div>
<div class="panel-footer" style="height:100px;">'.$name.'
</div></a>
</div>
</div>';
}
}
mysqli_close($dbconnect);
?>
$dbconnect is undefined in your script. Also rewrite your query:
$sql = "SELECT COUNT(stockID) FROM stock WHERE search LIKE ". $condition ." GROUP BY stockID"; I have added a space just before "Group By". Hope this will help.

search feature not work for certain words

The problem I faced is when search word "anti" it will display the product but when search based words "anti wrinkle" mentioned no search result. Please refer below for the code and advice what do I missed.
$search_output = '';
if(isset($_POST['search'])) {
$searchsql = $_POST['search'];
$searchsql = preg_replace('#[^a-z 0-9?!#-]#i', '', $searchsql);
$query = mysql_query("SELECT tb_spa_prd.*, tb_spa_prd_cat.spa_prd_cat FROM tb_spa_prd AS tb_spa_prd INNER JOIN tb_spa_prd_cat ON tb_spa_prd.spa_prd_cat_id = tb_spa_prd_cat.spa_prd_cat_id WHERE spa_prd_cat LIKE '%$searchsql%' or spa_prd_code LIKE '%$searchsql%' or spa_prd_name LIKE '%$searchsql%'") or die ("Could no search!");
$count = mysql_num_rows($query);
if($count == 0) {
$search_output .= '<tr>
<td colspan="9" style="text-align: center">There was no search results!</td>
</tr>';
} else {
$row_no = 1;
while($row = mysql_fetch_array($query,MYSQL_ASSOC)) {
$spa_prd_id = $row["spa_prd_id"];
$spa_prd_cat = $row["spa_prd_cat"];
$spa_prd_code = $row["spa_prd_code"];
$spa_prd_name = $row["spa_prd_name"];
$spa_prd_vlm = $row["spa_prd_vlm"];
$spa_prd_qty = $row["spa_prd_qty"];
$spa_prd_crt_date = $row["spa_prd_crt_date"];
$spa_prd_crt_usr = $row["spa_prd_crt_usr"];
$search_output .= '<tr>
<td>'.$row_no++.'</td>
<td>'.$spa_prd_cat.'</td>
<td>'.$spa_prd_code.'</td>
<td>'.$spa_prd_name.'</td>
<td>'.$spa_prd_vlm.'</td>
<td>'.$spa_prd_qty.'</td>
<td>'.$spa_prd_crt_date.'</td>
<td>'.$spa_prd_crt_usr.'</td>
<td><a href=\'edit_spa_prd.php?spa_prd_id='.$spa_prd_id.'\'>Edit</a> | <a href=\'delete_spa_prd.php?spa_prd_id='.$spa_prd_id.'\'>Delete</a></td>
</tr>';
} // close while loop
}
}
You can try explicitly including a LIKE predicate for each search term like this:
$searchsql = $_POST['search'];
$terms = explode(" ", $searchsql);
$likecols = array("spa_prd_cat", "spa_prd_code, "spa_prd_name");
$likesql = "";
foreach ($likecols as $likecol) {
for ($i = 0; $i < count($terms); ++$i) {
if ($likecol == "spa_prd_cat" && $i == 0) {
$likesql = "spa_prd_cat LIKE $terms[0]";
}
else {
$likesql .= " OR $likecol LIKE $terms[$i]";
}
}
}
$querystr = "SELECT tb_spa_prd.*, tb_spa_prd_cat.spa_prd_cat FROM tb_spa_prd AS tb_spa_prd INNER JOIN tb_spa_prd_cat ON tb_spa_prd.spa_prd_cat_id = tb_spa_prd_cat.spa_prd_cat_id WHERE ";
$querystr .= $likesql;
$query = mysql_query($querystr) or die ("Could no search!");

Search engine with multiple keywords

I have a search engine that is working , but only when I search 1 word. Whenever I search multiple keywords I only get 1 result.
Example : In my database I have tags like 'test' and 'hello' ;
Whenever I enter "test hello" and click "Search" it displays :
1 result hello (this being the title of the post with the tag = hello).
My code (search.php - the page where I get the search results):
<?php
$button = $_GET ['submit'];
$search = $_GET ['search'];
if(!$button) {
echo "you didn't submit a keyword";
} else {
if(strlen($search)<=1) {
echo "Search term too short";
} else {
echo "You searched for <b>$search</b> <hr size='1'></br>";
mysql_connect("localhost","root","root");
mysql_select_db("myschool");
$search_exploded = explode (" ", $search);
foreach($search_exploded as $search_each) {
$x = NULL;
$construct = NULL;
$x++;
if($x==1) {
$construct .="tag LIKE '%$search_each%'";
} else {
$construct .="OR tag LIKE '%$search_each%'";
}
$construct ="SELECT * FROM posts WHERE $construct";
$run = mysql_query($construct);
$foundnum = mysql_num_rows($run);
if ($foundnum==0) {
echo "Sorry, there are no matching result for <b>$search</b>.";
} else {
echo "$foundnum results found !<p>";
while($runrows = mysql_fetch_assoc($run)) {
$title = $runrows ['title'];
$tag = $runrows ['tag'];
echo "<a href='#'><b>$title</b></a><br>";
}
}
}
}
}
?>
Problem is probably around the $x=++ part , because I believe the engine is not displaying or even searching through all the rows in the database , and not displaying when the num row count > 1 .
Thanks in advance guys.
EDIT :
I now get multiple results with the code above BUT I get them in this form :
You searched for hello test postare
1 results found !
HELLO
1 results found !
Test
1 results found !
postare noua
How can I make it add the results in 1 place , and not say it everytime it finds a new result for a different keyword ?
You need to start $x variable before foreach statement, and dont set it as null if you want to use it as an integer.
The $construct variable has the same error, you must be having the same response for three times, thats because you have to close the foreach statement before calling mysql select.
$x = 1;
$construct = NULL;
foreach($search_exploded as $search_each)
{
if($x==1) {
$construct .="tag LIKE '%$search_each%'";
} else {
$construct .="OR tag LIKE '%$search_each%'";
}
$x++;
}
$select ="SELECT * FROM posts WHERE $construct";
...
Last Edit
<?php
$button = $_GET ['submit'];
$search = $_GET ['search'];
if(!$button) {
echo "you didn't submit a keyword";
} else {
if(strlen($search)<=1) {
echo "Search term too short";
} else {
echo "You searched for <b>$search</b> <hr size='1'></br>";
mysql_connect("localhost","root","root");
mysql_select_db("myschool");
$search_exploded = explode (" ", $search);
$x = 1;
$construct = '';
foreach($search_exploded as $search_each) {
if($x==1) {
$construct .="tag LIKE '%$search_each%'";
} else {
$construct .="OR tag LIKE '%$search_each%'";
}
$x++;
}
$select ="SELECT * FROM posts WHERE $construct";
$run = mysql_query($select);
$foundnum = mysql_num_rows($run);
if ($foundnum==0) {
echo "Sorry, there are no matching result for <b>$search</b>.";
} else {
echo "$foundnum results found !<p>";
while($runrows = mysql_fetch_assoc($run)) {
$title = $runrows ['title'];
$tag = $runrows ['tag'];
echo "<a href='#'><b>$title</b></a><br>";
}
}
}
}
?>
You have a couple issues on your code. You missed a " on this line:
echo "Sorry, there are no matching result for <b>$search</b>";
And the last else does not have an if

Mysqli multi_query Search of 2 Tables Not showing Results

I'm up to my neck trying to figure out why my query isn't working. This is what my search.php page results in. I am able to _GET the search term perfectly but can't display the results.
Not sure if the issue is the fetch_array_assoc or what! Here's my code. Any help with this would be appreciated. Not 100% sure if my syntax is correct.
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$button = $_GET ['submit'];
$search = $_GET ['query'];
if (strlen($search) <= 1) {
echo "Search term too short";
}
else {
echo "You searched for <b>$search</b> <hr size='1'></br>";
$con = new mysqli("localhost", "user", "pass", "db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$search_exploded = explode(" ", $search);
foreach ($search_exploded as $search_each) {
$x++;
if ($x == 1) {
$query = "Keyword_ID LIKE '%$search_each%' or Keyword_Name LIKE '%$search_each%' ";
}
else {
$query .= "OR Keyword_ID LIKE '%$search_each%' or Keyword_Name LIKE '%$search_each%' ";
}
}
$construct = mysqli_query($con, "SELECT * FROM profileTable WHERE $query");
$construct = mysqli_query($con, "SELECT * FROM addKeywordTable (Keyword_Name) WHERE $query");
$constructs = mysqli_multi_query($construct);
if (mysqli_multi_query($construct)) {
$numrows = mysqli_num_rows($query);
if ($numrows > 0) {
while ($row = mysqli_fetch_assoc($constructs)) {
$key = $row['Keyword_Name'];
$keyID = $row['keyID'];
$fname = $row['FirName'];
$lname = $row['LaName'];
$mname = $row['MName'];
$suffix = $row['Suffix'];
$title = $row['Title'];
$dept = $row['Dept'];
$phone1 = $row['PH1'];
$phone2 = $row['PH2'];
$email = $row['Email'];
$photo = $row['Photo'];
$bio = $row['BioLK'];
$tags = $row['Tags'];
echo '<h2>$fname $lname</h2>';
echo $key;
echo $title;
echo $dept;
}
}
else {
echo "Results found: \"<b>$x</b>\"";
}
}
}
mysqli_close();
?>
I am trying to search two different tables. addKeywordTable and profileTable. Profile table has all of the profile info for a user. The addKeywordTable stores the keywords/tag names 'Keyword_Name'.
I attempted to create a mysqli_multi_query but its not working at all.
I assuming:
$con is set by
$con = mysqli_connect("host", "user", "password", "db");
mysqli_multi_query : you must all sql commands, except the last, terminate with ;
and concenat $construct with .= . Otherwise you overwrite your $construct.
$construct = "SELECT * FROM profileTable WHERE $query ;");
$construct .= "SELECT * FROM addKeywordTable (Keyword_Name) WHERE $query");
don't set $construct with
$construct = mysqli_query($con, "SELECT * FROM profileTable WHERE $query");
your $construct will only become TRUE or FALSE .
with a variable wich contents TRUE or FALSEyou can not call
$constructs = mysqli_multi_query($con,TRUE);
And you call it wrong
$constructs = mysqli_multi_query($construct);
correct
$constructs = mysqli_multi_query($con,$construct);
You call mysqli_multi_query($construct) twice
$constructs = mysqli_multi_query($construct);
if (mysqli_multi_query($construct)) { ...
the first call is not necessary.
call it only with
if (mysqli_multi_query($con,$construct)) { ...
complete wrong is
if (mysqli_multi_query($construct)) {
$numrows = mysqli_num_rows($query);
if ($numrows > 0) {
while ($row = mysqli_fetch_assoc($constructs)) {
$query is at the moment a simple 'string'
$query = "Keyword_ID LIKE '%$search_each%' or Keyword_Name LIKE '%$search_each%' ";
Also wrong
while ($row = mysqli_fetch_assoc($constructs)) {
To retrieve the resultset from the first query you can use mysqli_use_result() or mysqli_store_result(). All subsequent query results can be processed using mysqli_more_results() and mysqli_next_result().
Call it like this instead
if (mysqli_multi_query($con,$construct)) {
if ($result = mysqli_store_result($con)) {
while ($row = mysqli_fetch_row($result)) {
printf("%s\n", $row[0]);
}
mysqli_free_result($result);
Set $x before you do $x++ .
$x = 0;
You can't be sure that $x is always automatically set to 0 .

paging next and previous links don't work!

can anyone help me with this code?the next and previous links don't work
$limit=20;
mysql_connect("localhost","root","");
mysql_select_db("autoschool") or die("Unable to select database");
$query = "select * from student";
$numresults=mysql_query($query);
$numrows=mysql_num_rows($numresults);
if ($numrows == 0)
{
echo "empty";
}
if (empty($s)) {
$s=0;
}
$query .= " limit $s,$limit";
$result = mysql_query($query) or die("Couldn't execute query");
$count = 1 + $s ;
while ($row= mysql_fetch_array($result)) {
$title = $row["id"];
echo "$count.)$title"."
" ;
$count++ ;
}
$currPage = (($s/$limit) + 1);
echo "
";
if ($s>=1) { // bypass PREV link if s is 0
$prevs=($s-$limit);
print " <<
Prev 10&nbsp ";
}
$pages=intval($numrows/$limit);
if ($numrows%$limit) {
$pages++;
}
if (!((($s+$limit)/$limit)==$pages) && $pages!=1) {
$news=$s+$limit;
echo " Next 20 >>";
}
$a = $s + ($limit) ;
if ($a > $numrows) { $a = $numrows ; }
$b = $s + 1 ;
echo "
Showing results $b to $a of $numrows
";
OMG, where to start?
Firstly, you're not processing $s at the beginning so the LIMIT statement will always 0,20.
Try something like:
if (isset ($_GET['page']) ){
$s=round($_GET['page'];
if($s<0) {
$s=0;
}
}
else {
$s=0;
}
...
$query .= " LIMIT ".($s*$limit).",$limit";
Then you need to add links the previous and next text:
if ($s>0) { // bypass PREV link if s is 0
echo 'Prev ';
}
...
echo echo 'Next ';
...
To be honest, I'd start again from scratch if I was you, the code is very messy. Write pseudo-code to plan the logic first, then code.
Your "next 20" and "prev 10" are simply text displays. They are not links to begin with. Further more you have no way of handling input. It appears your example is incomplete.

Categories