I'm fairly new to coding, so I'm open to critique as well as help. I'm trying to apply pagination to my search results. I have returned the results I need, applied the limit and managed to get the pagination controls to present properly. However, when I select "next" or "previous" the pages have no results on. I'm sure there is something fundamentally wrong, but I just can't spot it.
?php
include_once("db_connex.php");
if (isset ($_POST ['search'])) {
$searchq = $_POST ['search'];
$count_query = mysql_query("SELECT * FROM activejobs WHERE jobtitle LIKE '%$searchq%' OR region LIKE '%$searchq%' AND status= '1'");
$count = mysql_num_rows($count_query);
// pagination starts here
if (isset($_GET['page'])) {
$page = pre_replace("#[^0-9]#","",$_GET['page']);
}
else {
$page = 1;
}
$perPage = 3;
$lastPage = ceil($count / $perPage);
if ($page < 1) {
$page = 1;
}
else if ($page > $lastPage) {
$page = $lastPage;
}
$limit = "LIMIT " . ($page - 1) * $perPage. ", $perPage";
$query = mysql_query("SELECT * FROM activejobs WHERE jobtitle LIKE '%$searchq%' OR region LIKE '%$searchq%' AND status= '1' ORDER BY jobid DESC $limit");
}
if ($lastPage != 1) {
if ($page != $lastPage) {
$next = $page + 1;
$pagination .= 'Next';
}
if ($page != 1) {
$prev = $page - 1;
$pagination .= 'Previous';
}
}
while ($row = mysql_fetch_array($query)) {
$jobtitle = $row['jobtitle'];
$region = $row['region'];
$salary = $row['salary'];
$jobdescription = $row ['jobdescription'];
$joburl = $row ['joburl'];
$output .= '<div id= "searchresults"><div id= "applybutton">Details</div><font id= "resultstitle">'.$jobtitle.' - '.$region.' - '.$salary.'</font><br>'.$jobdescription.'</div>';
}
?>
This kinds of if-else hell:
// pagination starts here
if (isset($_GET['page'])) {
$page = pre_replace("#[^0-9]#","",$_GET['page']);
}
else {
$page = 1;
}
can be solved like this (default it at start):
// pagination starts here
$page = 1;
if (isset($_GET['page'])) {
$page = pre_replace("#[^0-9]#","",$_GET['page']);
}
or even this (if you feel adventurous):
$page = (isset($_GET['page']) ? pre_replace("#[^0-9]#","",$_GET['page']) : 1);
Making a lot of If-else is easy at start and hard later, so keep it simple by reducing when you have nothing to do. Making your code smaller in a step closer to any solution.
Also this is common:
...
while ($row = mysql_fetch_array($query)) {
$jobtitle = $row['jobtitle'];
$region = $row['region'];
...
Why assigning $jobtitle to $row['jobtitle']; ?
It doesnt make your code easier, it just adds more code and making you read harder.
Give $row['X'] directly.
Also, as #ojovirtual stated you need to pass "$search" parameter everytime, otherwise your entire code block will be ignored ("$search" is not set)
Finally, when working with MySQL you need to check the values you feed your queries with,
in this example the $searchq. A malicious coder could make the $searchq look like a part of the query.
There is a simple fix for that:
Instead of plain:
$count_query = mysql_query("SELECT * FROM activejobs WHERE jobtitle LIKE '%$searchq%' OR region LIKE '%$searchq%' AND status= '1'");
make it a habit doing this:
$searchq = mysql_real_escape_string($searchq);
$count_query = mysql_query("SELECT * FROM activejobs WHERE jobtitle LIKE '%$searchq%' OR region LIKE '%$searchq%' AND status= '1'");
Not a universal solution but a starter before dive into new technologies as a starter.
This is a must for fields like username, password etc.
Finally, change from:
if (isset ($_POST ['search'])) {
$searchq = $_POST ['search'];
to:
if (isset ($_GET['search'])) {
$searchq = $_GET['search'];
You need to pass search again in your next and previuos buttons. A quick fix would be:
Change $_POST to $_REQUEST:
if (isset ($_REQUEST ['search'])) ...
Add the search to your next and previousbuttons:
$pagination.= 'Next';
Same with the previous button.
As someone stated, you should do some input sanitation before any database query.
Related
I wonder how to make pagination in PHP
May I ask you a favor of you?
This code have not error.
But I do not know what $current_page make
<?php
$con = mysqli_connect("localhost", "root", "", "dbdb") or die("error");
$page_size = 10;
$page_list_size = 10;
if (isset($_POST['search'])) {
$valueTosearch = $_POST['valueTosearch'];
$query = "SELECT * FROM `shipment` WHERE CONCAT(`Ship_Date`,`Model_No`,`Serial_No`)LIKE'%" . $valueTosearch . "%' ORDER BY Ship_Date DESC LIMIT $page_size";
$search_result = filterTable($query);
} else {
$query = "SELECT * FROM `shipment` ORDER BY Ship_Date DESC LIMIT $page_size";
$search_result = filterTable($query);
}
function filterTable($query) {
$con = mysqli_connect("localhost", "root", "", "dbdb");
$filter_Result = mysqli_query($con, $query);
return $filter_Result;
}
echo "<center><h1>info</h1></center> <br><br>";
$ret = mysqli_query($con, $query);
if ($ret) {
echo mysqli_num_rows($ret), " <br><br>";
$count = mysqli_num_rows($ret);
} else {
echo "error :" . mysqli_error($con);
exit();
}
$query = "SELECT count(*) FROM shipment";
$result_count = mysqli_query($con, $query);
$result_row = mysqli_fetch_array($result_count);
$total_row = $result_row[0];
if ($total_row <= 0)
$total_row = 0;
$total_page = ceil($total_row / $page_size);
$current_page = ceil();
?>
I wonder how to make pagination in PHP
May I ask you a favor of you?
This code have not error.
But I do not know what $current_page make
I think you have a mistake on the mysql query, limitting to $page_size you will get only a number of results = $page_size, but you will always get the $page-size 1st elements, if you want to page results you need to add offset.
This way first page will be $page_size elements with offset 0, second page $page_size elements with $page_size offset, and in general the nth page will be $page_size elements with (n-1) times $page_size offset.
In the last line you are missing an argument:
$current_page = ceil(); should be $current_page = ceil($lowest_element_in_result_set/$page_size);
$current_page should be the number of the page user want to view and this would be a input from user.
this is my implementation.
hope this will help you .
$pagenum = $_GET['pagenum'];//get the page number user want to view
$con = mysqli_connect("localhost", "root", "9272", "new_platform_7");
$query = 'select * from table1';
$filter_Result = mysqli_query($con, $query);//execute query without limit to get total number of rows
$rows = mysqli_num_rows($filter_Result);//total number of rows
if (!(isset($pagenum)))
{
$pagenum = 1;//if user hasn't give page number set page to page number 1
}
$page_rows = 30;//the page size (number of rows in each page)
$last = ceil($rows/$page_rows);//total number of pages //use ceil to avoid fractions
if ($pagenum < 1){ //if user give negative page number. set page number to 1
$pagenum = 1; //this will happen if user clicked the Previous page link when current page is 1
}elseif ($pagenum > $last) //if page number is greater than calculated number of pages . set page number to last page
{
$pagenum = $last; //this will happen if user clicked the next page link when current page is the last page
}
//($pagenum - 1) * $page_rows calculates where to start the lmit
$query.= ' limit ' .($pagenum - 1) * $page_rows .',' .$page_rows;//limit result
echo $query;
$filter_Result = mysqli_query($con, $query);//execute query with limits
//pagination links
echo 'First Page';
echo 'Previous Page';
echo 'Next Page';
echo 'Last Page';
Try this in a simple way.
<?php
$link = mysqli_connect("localhost","roo","","dbname");
if(!$link):
echo "something wrong with the database connection";
endif;
//check to see if the page (value) is available
if(isset($_GET['pageNo']):
$page = $_GET['pageNo'];
else:
$page = "";
endif;
if($page == "" || $page == 1):
$start_to_count_rowNo = 0;
else:
$start_to_count_rowNo = ($page * &item_displayed_per_page) - &item_displayed_per_page;
endif;
//here choose how many items do you want to display per page
&item_displayed_per_page = 10;
//Now select the data to display them
$query = "SELECT * FROM table_name LIMIT $start_to_count_rowNo, $item_displayed_per_page";
$readData = mysqli_query($link, $query);
//obtaining total number of data(rows) in a database
$sql = mysqli_query($link,"SELECT * FROM table_name");
$total_row = mysqli_num_rows($sql);
$pageNo = ceil($total_row / &item_displayed_per_page);
//using bootstrap add class pager in unordered list to style the list
?>
<ul class="pager">
<?php
//display out the page # like 1,2,3 ....
for($i = 0; $i <= $pageNo; $i++){
echo "</li><a href='pagename.php?pageNo={$i}'>{$i}</a></li>";
}
?>
</ul>
I have a table called "product".
I'm displaying all the data from PHP product view page by using the id parameter.
With my code:
if(isset($_GET['id'])) {
$id = $_GET['id'];
}
$query = "SELECT * FROM product WHERE id = $id ";
$select_product = $db->query($query);
while($row = $db->fetch_object($select_product)) {
$status = $row->status;
if($status == 'published') {
$title = $row->title;
echo $title;
}
}
I can pull all the data I need. In this example I can echo the title.
But how do I display a dynamic next page link? That goes same for previous link.
When I try with this code:
$query = "SELECT id FROM product";
$select_ids = $db->query($query);
while($row = $db->fetch_object($select_ids)) {
$ids = $row->id;
echo $ids;
}
I can see all the pages from that table. In my case they are 20,21,22...28
Next, I've tried like this:
$query = "SELECT id from product";
$select_ids = $db->query($query);
if($select_ids->num_rows > 0) {
$next = $id + 1;
echo 'Next';
} else {
}
With this code, my "next" link successfully goes to the next page. But, when it finishes with the result, in this case when I'm on page 28, the next dynamic link goes to empty page (29). Also this is not a good approach, because if some page, let's say 25 is deleted, the next link won't skip that page.
How can I improve that dynamic "next" link?
So first of all, you need two queries one for getting the data to display and another for counting the number of rows, also we'll need some additional variables.
Here comes the code:
$page = 1;
if(isset($_GET['page'])) {
$page = $_GET['page'];
}
$numberOfResultsPerPage = 10;
$offset = $numberOfResultsPerPage * ($page - 1)
$count = $db->query("SELECT COUNT(id) as num FROM product");
while($row = $db->fetch_object($count)) {
$numberOfRows = $row->num;
}
$query = "SELECT id FROM product LIMIT ". $offset.", ".$numberOfResultsPerPage;
$select_ids = $db->query($query);
while($row = $db->fetch_object($select_ids)) {
$ids = $row->id;
echo $ids;
}
if($page > 1) {
echo 'Prev';
}
if($page < ceil($numberOfRows / $numberOfResultsPerPage)) {
echo 'Next';
}
UPDATE:
In case you need to just find the next and previous product of the product this is the solution. It is not good if you'll have lots of products but in case the number of products is under 1000 there should not be any problems:
if(isset($_GET['id'])) {
$id = $_GET['id'];
}
$query = "SELECT id from product";
$select_ids = $db->query($query);
$ids = array();
$i = 0;
while($row = $db->fetch_object($select_ids)) {
$ids[$i] = $row->id;
if($row->id == $id) {
$index = $i;
}
$i++;
}
if(isset($ids[$index-1])) {
echo 'Prev';
}
if(isset($ids[$index+1])) {
echo 'Next';
}
new Query
$query = "SELECT COUNT(*) FROM payments $sCriteria";
$result = mysql_query($query) or die("Error encountered on retrieving logs.");
$query_data = mysql_fetch_row($result);
$numrows = $query_data[0];
$rows_per_page = 30;
$lastpage = ceil($numrows/$rows_per_page);
$pageno = (int)$pageno;
if ($pageno > $lastpage) {
$pageno = $lastpage;
}
if ($pageno < 1) {
$pageno = 1;
}
$limit = "LIMIT ".($pageno - 1) * $rows_per_page .",".$rows_per_page;
$rs = mysql_query("SELECT * FROM payments $sCriteria ORDER BY pay_date DESC $limit") or die("Error encountered on retrieving logs.".mysql_error());
$current_rows = mysql_num_rows($rs);
if ($current_rows) {
while ($rows = mysql_fetch_array($rs)) {
echo "<tr>
<td>".date("m/d/Y n:H:s",strtotime($rows["pay_date"]))."</td>
<td>".$rows["po_no"]."</td>
<td>".$rows["or_no"]."</td>
<td>".$rows["sold_to"]."</td>
<td>Php ".number_format($rows["amt_to_pay"],2,".",",")."</td>
<td>Php ".number_format($rows["amt_paid"],2,".",",")."</td>
<td>".$rows["pay_status"]."</td>
**<td>".$rows["verified"]."</td>**
<td><a href='pay_preview.php?id=$iPayID' class='action preview' title='Print Preview'><img src='images/preview.png' class='action_img' /></a></td>
Old Query
$query = "SELECT COUNT(*) FROM payments";
$result = mysql_query($query) or die("Error encountered on retrieving payment details.");
$query_data = mysql_fetch_row($result);
$numrows = $query_data[0];
$rows_per_page = 10;
$lastpage = ceil($numrows/$rows_per_page);
$pageno = (int)$pageno;
if ($pageno > $lastpage) {
$pageno = $lastpage;
}
if ($pageno < 1) {
$pageno = 1;
}
$limit = "LIMIT ".($pageno - 1) * $rows_per_page .",".$rows_per_page;
$rs = mysql_query("SELECT * FROM payments ORDER BY pay_date DESC, po_id $limit") or die("Error encountered on retrieving payment details.");
$current_rows = mysql_num_rows($rs);
if ($current_rows) {
while ($rows = mysql_fetch_array($rs)) {
$iPayID = $rows["pay_id"];
$iPoID = $rows["po_id"];
$dSubTotal = get_po_subtotal($iPoID);
$sPoNo = get_value("po","po_no","WHERE po_id=$iPoID");
$iDis = get_value("po","discount","WHERE po_id=$iPoID");
$dNet = $dSubTotal - ($dSubTotal * ($iDis/100));
$sStat = $rows["pay_status"];
switch($sStat) {
case "Paid": $sColor = "class='blue'";break;
default: $sColor = "";break;
}
if ($rows["verified"]) {
$sVerified = "Yes";
}
else {
$sVerified = "No <a href='payment_verification.php?id=$iPayID' class='action verify' title='Verify' id='$iPayID'>(verify)</a>";
}
echo "<tr>
<td>".date('Y-m-d',strtotime($rows["pay_date"]))."</td>
<td>".$rows["or_no"]."</td>
<td>$sPoNo</td>
<td>".$rows["sold_to"]."</td>
<td class='right'>Php ".number_format($rows["amt_to_pay"],2,".",",")."</td>
<td class='right'>Php ".number_format($rows["amt_paid"],2,".",",")."</td>
<td $sColor>".$rows["pay_status"]."</td>
<td>$sVerified</td>
<td><a href='pay_preview.php?id=$iPayID' class='action preview' title='Print Preview'><img src='images/preview.png' class='action_img' /></a></td>
</tr>\n";
}
}
My problem is that on my new query I can't change the Verified output to Paid or Unpaid, It stays with a 0 and 1 ** I did also copy and compare it with my old and new query, it just that it didn't work, can someone help me with it? thank you so much.
I would suggest something like as an example to use a condition in mysql:
I your SQL statement specify the columns and don't use SELECT *
SELECT IF(Field > 0,'TRUE','FALSE') AS verified FROM Table
You can add a field to change it to paid or unpaid as well
SELECT IF(Field > 0,'Paid','Unpaid') AS verified FROM Table
Serves as an example. you can add any condition and result output
ALSO
In you code I cannot determine where $sVerified is ever assigned a value?
I am not sure exactly what your asking.. I don't know if your needing to print the value to the page, or if your needing to change it for another query..
Maybe a switch case would work.. Allowing you to change the format to however you need it. Basically converting your old queries result so your new query can handle it..
$value = 0; // or false.. this is your value from first query
$newval = null; // just placeholder for newval in switch
switch($value) {
case 0:
$newval = 'Unpaid';
break;
case 1:
$newval = 'Paid';
break;
default:
$newval = 'Unknown';
}
echo $newval;
So I was trying to do pagination with php, but I can't quite get it done, there is an error of undefined index page in it somewhere, I have no idea why...here is my code:
<?php
$perpage = 10;
if (empty($_GET['page'])) {
$page = 1;
}else{
$page = $_GET['page'];
}
$limitstart = $_GET['page'] - 1 * $perpage;
$query = "SELECT * FROM images ORDER BY id DESC LIMIT '".$limitstart."', '".$perpage."' ";
$result = mysqli_query($con,$query) or die(mysqli_error($con));
while($row=mysqli_fetch_array($result)) {
?>
I appreciate your help in any way, thank you.
$limitstart = $_GET['page'] - 1 * $perpage;
is the same as (remember your math class)
$limitstart = $_GET['page'] - (1 * $perpage);
You would like to use
$limitstart = ($page - 1) * $perpage;
(also note the usage of your $page-variable)
The following code is working fine for the first page. It is a query based on user input from a form. I have 2 issues. The first one is when i click next page i get undefined index and undefined variable error which means the variables are not passed. The second question is how can i make a query and paginate it based on the user filled/selected values in the form? Some users may not fill all the values.
Here is my code: NB: The form method is GET. I have tried REQUEST and POST too. All the same error. Thanks in advance guys.
<?php
if (isset($_POST['Submit']))
$name = mysql_real_escape_string($_GET['name']);
$email = mysql_real_escape_string($_GET['email']);
$age = mysql_real_escape_string($_GET['age']);
$height = mysql_real_escape_string($_GET['height']);
include_once "conn.php"; //connect to db and table
$rs = mysql_query("SELECT COUNT(*) FROM people WHERE name='$name' AND email='$email' AND age='$age' AND height='$height'");
$rw = mysql_fetch_array($rs);
$numrows = $rw[0];
if ($numrows== 0) die("No Results Found");
$rowsperpage = 7;
$totalpages = ceil($numrows / $rowsperpage);
if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) {
$currentpage = (int) $_GET['currentpage'];
} else {
$currentpage = 1;
}
if ($currentpage > $totalpages) {
$currentpage = $totalpages;
}
if ($currentpage < 1) {
$currentpage = 1;
}
$offset = ($currentpage - 1) * $rowsperpage;
$query = mysql_query("SELECT * FROM people WHERE name='$name' AND email='$email' AND age='$age' AND height='$height' ORDER BY time DESC LIMIT $offset, $rowsperpage");
//print my tables here
while($row = mysql_fetch_array($query))
{
$uniqueid = $row['age'];
//output stuff here
}
//close sql
$range = 3;
if ($currentpage > 1) {
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=1&name=$name&email=$email&age=$age&height=$height'> Go To Page 1</a> ";
$prevpage = $currentpage - 1;
echo "<a href='{$_SERVER['PHP_SELF']}?currentpage=$prevpage&name=$name&email=$email&age=$age&height=$height'> Previous Page</a>";
}
for ($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) {
if (($x > 0) && ($x <= $totalpages)) {
if ($x == $currentpage) {
echo " <font size=4 color=red>[<b>$x</b>] </font>";
} else {
echo "<a href='{$_SERVER['PHP_SELF']}?currentpage=$x&name=$name&email=$email&age=$age&height=$height'>$x</a>";
}
}
}
if ($currentpage != $totalpages) {
$nextpage = $currentpage + 1;
echo "<a href='{$_SERVER['PHP_SELF']}?currentpage=$nextpage&name=$name&email=$email&age=$age&height=$height'>Next Page</font></a>";
echo "<a href='{$_SERVER['PHP_SELF']}?currentpage=$totalpages&name=$name&email=$email&age=$age&height=$height'>Last Page</a> ";
}
?>
The form submits as GET. Because this one, the POST variable isn't set. And you're not defining the first variable (missing brackets?). Furthermore, Submit is the only submitted value with a capital. Is this intentional?
if (isset($_GET['Submit'])) {
$name = mysql_real_escape_string($_GET['name']);
$email = mysql_real_escape_string($_GET['email']);
$age = mysql_real_escape_string($_GET['age']);
$height = mysql_real_escape_string($_GET['height']);
}
More ideally, because you want to ommit values, you'll probably want to check each variable individually for existence. And if it's not set (or empty), don't add that field in your WHERE clause.
$name = isset($_GET['name']) ? mysql_real_escape_string($_GET['name']) : null;
// ... process the other fields in same way ...
or spanned over multiple lines: EDIT: just noticed I was missing a closing ) in the two blocks below.
$name = null;
if (isset($_GET['name'])) {
$name = mysql_real_escape_string($_GET['name']);
}
// ... process the other fields in same way ...
or even:
$name = null;
if (isset($_GET['name']))
$name = mysql_real_escape_string($_GET['name']);
// ... process the other fields in same way ...
Dynamic query
Then, make your query a bit more dynamic. Like, adding all your available WHERE parameters to an array. It makes things easier.
// Store conditions in array
$whereConditions = array();
if (!empty($name)) {
$whereConditions['name'] = $name;
}
if (!empty($email)) {
$whereConditions['email'] = $email;
}
if ($age && $age > 0) {
$whereConditions['age'] = $age;
}
if ($height && $height > 0) {
$whereConditions['height'] = $height;
}
// Start building your query dynamically
$query = 'SELECT * FROM people';
// Making things easier here. Just flatten your array down.
$conditions = array();
foreach ($whereConditions as $field => $value) {
$conditions[] = sprintf("%s = '%s'", $field, $value);
}
// Join all conditions with AND
$where = implode(' AND ', $conditions);
// Add where clause, if there are conditions
if (!empty($where)) {
$query .= ' WHERE ' . $where;
}
$query .= " ORDER BY time DESC LIMIT {$offset}, {$rowsperpage}";
Final notes
Keep in mind to use prepared queries if you're allowing user input. And the mysql_ extension is deprecated. Switch to mysqli_ or PDO.