Call a function without its parameters - php

Below are the functions that am using to make reusable pagination. If you see the code below, theirs a function
generate_pages()
which is taking parameters from function
paged_controls()
But I would like to call the function generate_pages() without passing any parameters on body.php.
This is the error message am getting on body.php when calling function
generate_pages()
Warning: Missing argument 1 for generate_pages(), called in
E:\admin\snippets\body.php on line 11 and defined in
E:\admin\cores\pages.php on line 12
Notice: Undefined variable: limit in E:\xampp\htdocs\projects\hoplate\admin\cores\pages.php on line 16
Is that possible?
pages.php
<?php
function page_count(){
global $db;
$sql = "SELECT COUNT(pages_id) FROM pages";
$query = $db->SELECT($sql);
$rows = $db->FETCH_ROW();
foreach($rows as $row){
return $row[0];
}
}
function generate_pages($limit){
/* Run actual query now to get the records from database */
global $db;
$sql = "SELECT * FROM pages " . $limit;
$query = $db->SELECT($sql);
return $rows = $db->FETCH_OBJECT();
}
function paged_controls($page_rows = 1){
global $db;
/* Call the function page_count to get the total page count */
$row_count = page_count();
/* We use the ceil function to round the number to whole number */
$last = ceil($row_count / $page_rows);
/* Make sure that the last page cannot be less then 1 */
if($last < 1){
$last = 1;
}
/* Est. the page number variables */
$pagenum = 1;
/* Set the pagenum variables from URL else set it to 1*/
if(isset($_GET["paged"])){
$pagenum = preg_replace('#[^0-9]#', '', $_GET["paged"]);
}
/* Make sure page number canoot be less then 1 */
if($pagenum < 1){
$pagenum = 1;
} else if($pagenum > $last){
$pagenum = $last;
}
/* Set the range of query to be excuted depend on our variables values set*/
$limit = 'LIMIT '.($pagenum - 1) * $page_rows . ','. $page_rows;
generate_pages($limit);
$paged_controls = "";
/* Only if theirs more then 1 page of results */
if($last != 1){
if($pagenum > 1){
$previous = $pagenum - 1;
$paged_controls .= 'Previous ';
/* Renders the left paged numbers */
for($i = $pagenum - 4; $i < $pagenum; $i++){
if($i > 0){
$paged_controls .= ''.$i.' ';
}
}
}
/* Render the current page the user is at */
$paged_controls .= ''.$pagenum.' ';
/* Renders the right paged numbers */
for($i = $pagenum + 1; $i <= $last; $i++){
$paged_controls .= ''.$i.' ';
if($i >= $pagenum + 4){
break;
}
}
if($pagenum != $last){
$next = $pagenum + 1;
$paged_controls .= 'Next ';
}
return $paged_controls;
}
}
?>
body.php
<?php
$pages = generate_pages();
foreach($pages as $page){
echo $pages_id = $page->pages_id . "<br/>";
}
?>

Only way I would see this working is adding a check.
function generate_pages($limit = null){
/* Run actual query now to get the records from database */
$gloab $db;
$sql = "SELECT * FROM pages " . isset($limit) ? "LIMIT $limit" : "";
$query = $db->SELECT($sql);
return $rows = $db->FETCH_OBJECT();
}
So now it could be run one of two ways
generate_pages();
or:
generate_pages(10);

Compare both of your function headers:
function generate_pages($limit)
function paged_controls($page_rows = 1)
PHP offers you to specify default arguments, just like C++ (you have to scroll down a bit to see the section).
Your paged_controls-function already does this and it is a great way of achieving what you want without editing the business logic within the function.
A default argument kicks in whenever you call a function without any parameters.
So, if you edit
function generate_pages($limit)
to (for example)
function generate_pages($limit = 'LIMIT 0,18446744073709551615')
and call the function via generate_pages(), PHP will automatically assume $limit = 'LIMIT 0,18446744073709551615'.
In this specific case, calling generate_pages without a parameter will retrieve all entries in the table you select from, as we tell the database to give us 18446744073709551615 entries from the beginning.
See the MYSQL manual on select/limit.

Related

PDO pagination query not executed correctly?

I'm currently trying to make some pagination work, but without any success.
The first query I'm executing is to grab all the data needed: so first result should be on the first page, second result on the second and so on... But I'm always getting the first result. Although I copied the query into phpmyadmin to manualy set the query and there it showed me the right results.
Here's the code where everything is happening. I'm stuck why it won't work.
$page = isset($_GET['page']) ? $_GET['page'] : 1;
$limit = 1;
$start = 0;
$query = $db->prepare("SELECT * FROM `users` LIMIT $limit OFFSET $start");
$query->execute();
$result = $query->fetchAll(PDO::FETCH_OBJ);
$count = count($result);
$query2 = $db->prepare("SELECT * FROM `users`");
$query2->execute();
$result2 = $query2->fetchALL(PDO::FETCH_OBJ);
$count2 = count($result2);
// Pagination
$total = ceil($count2 / $limit);
if ($page > 1) {
$start = ($page - 1) * $limit;
}
if ($page != $total) {
$next_page = '<li>»</li>';
} else {
$next_page = '<li class="disabled">»</li>';
}
if ($page > 1) {
$previous_page = '<li>«</li>';
} else {
$previous_page = '<li class="disabled">«</li>';
}
What am I doing wrong?
You are doing nothing with $page. $start is always 0 in the query.
You're going to need to define how many records you want per page, then multiply that by $page -1, e.g.
$start = ($page - 1) * $records_per_page;

Pagination for foreach loop

I currently have a method inside my "car class" that display the car:
static function getCars(){
$autos = DB::query("SELECT * FROM automoviles");
$retorno = array();
foreach($autos as $a){
$automovil = automovil::fromDB($a->marca, $a->modelo, $a->version, $a->year, $a->usuario_id, $a->kilometraje, $a->info,
$a->hits, $a->cilindrada, $a->estado, $a->color, $a->categoria, $a->precio, $a->idAutomovil);
array_push($retorno, $automovil);
}
return $retorno;
}
In my index.php I call that function
foreach(car::getCars() as $a){
That allows me to display the info this way ( of course inside the foreach I have a huge code with the details I'll display.
Is there a way to implement a pagination to that thing so I can handle 8 cars per page, instead of showing all of them at the same page?
You can add a $limit and $page parameter on your function so that it will only return a maximum of $limit number of items starting from $limit * $page(or will call it the $offset). You also need to add a function to get the total number of rows you have for automoviles table.
static function getCars($page = 0, $limit = 8){
$offset = $limit * max(0, $page - 1);
//replace this with prepared statement
$autos = DB::query("SELECT * FROM automoviles LIMIT $offset, $limit");
$retorno = array();
foreach($autos as $a){
$automovil = automovil::fromDB($a->marca, $a->modelo, $a->version, $a->year, $a->usuario_id, $a->kilometraje, $a->info,
$a->hits, $a->cilindrada, $a->estado, $a->color, $a->categoria, $a->precio, $a->idAutomovil);
array_push($retorno, $automovil);
}
return $retorno;
}
static function getTotal()
{
//query to get total number of rows in automoviles table
}
In your index.php do this:
foreach(car::getCars((isset($_GET['page']) ? $_GET['page'] : 1)) as $a){
...
}
and add the pagination links.
$total = car::getTotal();
if($total > 8) {
for($i = 1; $i <= intval(ceil(1.0 * $total / $limit)); $i++) {
echo '' . $i . ';
}
}

having trouble to integrate search results with pagination

I got the pagination controls and my search results shows 5 results fine. but when I click the second page, all of the search results go away. even though for what I searched, there is more than 5 results in the database. if you would please see the update code in just a second. here is my email bud just in case: raminrahim [at] hotmail [dot] com Please. thanks.
<?php
$paginationCTRLS = '';
$textline1 = '';
$textline2 = '';
$list = '';
if (isset($_GET['search_item'])) {
$search_item = $_GET['search_item'];
if (!empty($search_item)) {
if (strlen($search_item)>=3) {
// This query is just to get total count of rows
$query= "SELECT COUNT(item_id) FROM items"; // $sql
$query_run = mysqli_query($mysqli, $query); // $query
$query_row = mysqli_fetch_row($query_run); // $row
// $rows: here we have the total row count
$rows = $query_row[0]; // pgRows = row[]
// This is the number of results we want displayed per page
$page_rows = 5;
// This tells us the page number of our last page
$last = ceil($rows/$page_rows);
// This makes sure last cannot be less than 1.
if ($last < 1)
{
$last = 1;
}
// Establish the $pagenum variables
$pagenum = 1;
// Get pagenum from URL vars if it present, else it is = 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;
$query = "SELECT `item_id`, `featured_Items` FROM `items` WHERE
`featured_Items` LIKE
'%".mysql_real_escape_string($search_item)."%' $limit";
$query_run = mysqli_query($mysqli, $query);
$query_num_rows = mysqli_num_rows($query_run);
if ($query_num_rows>=1)
{
echo $query_num_rows. ' results found:<br>' . '<br>';
while ($query_row = mysqli_fetch_assoc($query_run))
{
echo $query_row['featured_Items'].'<br>' . '<hr>';
}
}
else
{
echo 'No result found' . '<hr>';
}
} else {
echo 'Not enough keywords to predict your search' . '<hr>';
}
}
$textline1 = "Result:" . '(<b>$rows</br>)';
$textline2 = "Page <b>" . '$pagenum' . "</b> of <b>" . '$last' . "</b>";
if ($last != 1){
if ($pagenum > 1) {
$previous = $pagenum - 1;
$paginationCTRLS .= 'Back ';
for($i = $pagenum-4; $i < $pagenum; $i++){
if($i>0){
$paginationCTRLS .= ''.$i.' ';
}
}
}
$paginationCTRLS .= ''.$pagenum.' ';
for ($i = $pagenum+1; $i <= $last; $i++) {
$paginationCTRLS .= ''.$i.' ';
if($i >= $pagenum+4) {
break;
}
}
if ($pagenum != $last) {
$next = $pagenum +1;
$paginationCTRLS .= ' Next ';
}
}
$list = '';
while($row = mysqli_fetch_array($query_run, MYSQLI_ASSOC)) {
$id = $row["item_id"];
$availablesITEMS = $row["featured_Items"];
$list .= '<p>'.$availablesITEMS.'<br>.</p>';
}
}
echo $list . '<br/>';
echo $paginationCTRLS . '<br/>';
?>
You need to set up your query to be able to accept an start point.
Like this:
LIMIT 0, 10
Where the first number corresponds to the starting row your results are going to be obtained from, and the second number equals the amount of results you're going to get from that point on.
So in the sense of your code you'd have to set it up as:
$query = "SELECT `item_id`, `featured_Items` FROM `items` WHERE
`featured_Items` LIKE
'%".mysql_real_escape_string($search_item)."%'
LIMIT ".($pagenum-1)*5.",5";
Let me know if that clears up your doubt.
Edit:
As for enabling pagination through your means, simply change the method in your form to be a GET statement.
<form action="your_page.php" method="get">
Then from your code you can use the
$_GET['search_item']
method instead of POST. This in turn enables you to use those variables on your anchor tags for your pagination.
$paginationCTRLS .= ''.$i.' ';`
Edit2:
You have this piece of code:
for($i = $pagenum-4; $i < $pagenum; $i++){
if($i>0){
$paginationCTRLS .= ''.$i.' ';
}
}
This will always at any point output the same number of pages, which is 5.
Now what you need is something that outputs only the pagination that you really need. So for example setting up this variable:
$pages = ceil($row/$page_rows);
Gives you your total amount of pages, then you can iterate to it:
for($i = 1; $i <= $pages; $i++){
if($i>0){
$paginationCTRLS .= ''.$i.' ';
}
}

php mysqli prepared statement search result pagination, link to next page show empty

solved ..basically as hinted by YourCommonSense, using the get variable to pass through the search query so i added these chunck of code in on top and edited the linkable url to passthrough the variable.
if (isset($_GET['searchquery'])){
$searchquery=$_GET['searchquery'];
$stmt = $myConnection->prepare('SELECT COUNT(id) FROM products WHERE product_name LIKE ? OR details LIKE ? OR category LIKE ? OR subcategory LIKE ? OR price LIKE ?');
$param = "%$searchquery%";
$stmt->bind_param('sssss', $param, $param, $param, $param, $param);
$stmt->execute();
/* store result */
$result=$stmt->bind_result($id);
$rows=array();
while ($stmt->fetch()){
$rows[]=array(
'id' => $id
);
}
$rows=$id;
// This is the number of results we want displayed per page
$page_rows = 4;
// This tells us the page number of our last page
$last = ceil($rows/$page_rows);
// This makes sure $last cannot be less than 1
if($last < 1){
$last = 1;
}
// Establish the $pagenum variable
$pagenum = 1;
// Get pagenum from URL vars if it is present, else it is = 1
if(isset($_GET['pn'])){
$pagenum = preg_replace('#[^0-9]#', '', $_GET['pn']);
}
// This makes sure the page number isn't below 1, or more than our $last page
if ($pagenum < 1) {
$pagenum = 1;
} else if ($pagenum > $last) {
$pagenum = $last;
}
$stmt=$myConnection->prepare('SELECT id,product_name,price FROM products WHERE product_name LIKE ? OR details LIKE ? OR category LIKE ? OR subcategory LIKE ? OR price LIKE ? LIMIT ?,?');
$begin= ($pagenum - 1) * $page_rows;
$end= $page_rows;
$stmt->bind_param('sssssii', $param, $param, $param, $param, $param,$begin,$end);
$stmt->execute();
/* store result */
$stmt->store_result();
/* get the row count */
$count = $stmt->num_rows;
if ($count >= 1) {
$stmt->bind_result($id, $product_name, $price);
$search_output = "<hr />$count results for <strong>$searchquery</strong><hr />";
$textline1 = "<h4><center>Total of <b>$rows</b> items in this section</center></h4>";
$textline2 = "Page <b>$pagenum</b> of <b>$last</b>";
// Establish the $paginationCtrls variable
$paginationCtrls = '';
// If there is more than 1 page worth of results
if($last != 1){
/* First we check if we are on page one. If we are then we don't need a link to
the previous page or the first page so we do nothing. If we aren't then we
generate links to the first page, and to the previous page. */
if ($pagenum > 1) {
$previous = $pagenum - 1;
$paginationCtrls .= 'Previous ';
// Render clickable number links that should appear on the left of the target page number
for($i = $pagenum-4; $i < $pagenum; $i++){
if($i > 0){
$paginationCtrls .= ''.$i.' ';
}
}
}
// Render the target page number, but without it being a link
$paginationCtrls .= ''.$pagenum.' ';
// Render clickable number links that should appear on the right of the target page number
for($i = $pagenum+1; $i <= $last; $i++){
$paginationCtrls .= ''.$i.' ';
if($i >= $pagenum+4){
break;
}
}
// This does the same as above, only checking if we are on the last page, and then generating the "Next"
if ($pagenum != $last) {
$next = $pagenum + 1;
$paginationCtrls .= ' Next ';
}
}
while ($stmt->fetch()) {
"$id, $product_name, $price";
$search_output .= "
<li><div class='product'>
<a href='product.php?id=$id' class='info'>
<span class='holder'>
<img src='inventory_images/$id.jpg' alt='$product_name' />
<span class='book-name'>$product_name</span>
</a>
<a href='product.php?id=$id' class='buy-btn'>RM<span class='price'>$price</span></a>
</div>
</li>
";
}
}
}
as mentioned in the question, i try to do my search result paginated. Everything else work, but the last little bit is when I click my paginatedCrls button go to next page or specific page, i loaded and show as a fresh new search. how do i fix this?
<?php
session_start();
$search_output = "";
if (empty($searchquery))
{ $search_output = "<hr />Please enter a search term in the above search box <hr />";}
if (isset($_POST['searchquery']) && $_POST['searchquery'] != "") {
$searchquery = preg_replace('/[^a-zA-Z0-9_ %\[\]\/\.\(\)%&-]/s', '', $_POST['searchquery']);
if ($_POST['filter1'] == "Products") {
require_once ("storescripts/connect_to_mysqli.php");
$stmt = $myConnection->prepare('SELECT COUNT(id) FROM products WHERE product_name LIKE ? OR details LIKE ? OR category LIKE ? OR subcategory LIKE ? OR price LIKE ?');
$param = "%$searchquery%";
$stmt->bind_param('sssss', $param, $param, $param, $param, $param);
$stmt->execute();
/* store result */
$result=$stmt->bind_result($id);
$rows=array();
while ($stmt->fetch()){
$rows[]=array(
'id' => $id
);
}
$rows=$id;
// This is the number of results we want displayed per page
$page_rows = 4;
// This tells us the page number of our last page
$last = ceil($rows/$page_rows);
// This makes sure $last cannot be less than 1
if($last < 1){
$last = 1;
}
// Establish the $pagenum variable
$pagenum = 1;
// Get pagenum from URL vars if it is present, else it is = 1
if(isset($_GET['pn'])){
$pagenum = preg_replace('#[^0-9]#', '', $_GET['pn']);
}
// This makes sure the page number isn't below 1, or more than our $last page
if ($pagenum < 1) {
$pagenum = 1;
} else if ($pagenum > $last) {
$pagenum = $last;
}
$stmt=$myConnection->prepare('SELECT id,product_name,price FROM products WHERE product_name LIKE ? OR details LIKE ? OR category LIKE ? OR subcategory LIKE ? OR price LIKE ? LIMIT ?,?');
$begin= ($pagenum - 1) * $page_rows;
$end= $page_rows;
$stmt->bind_param('sssssii', $param, $param, $param, $param, $param,$begin,$end);
$stmt->execute();
/* store result */
$stmt->store_result();
/* get the row count */
$count = $stmt->num_rows;
if ($count >= 1) {
$stmt->bind_result($id, $product_name, $price);
$search_output = "<hr />$count results for <strong>$searchquery</strong><hr />";
$textline1 = "<h4><center>Total of <b>$rows</b> items in this section</center></h4>";
$textline2 = "Page <b>$pagenum</b> of <b>$last</b>";
// Establish the $paginationCtrls variable
$paginationCtrls = '';
// If there is more than 1 page worth of results
if($last != 1){
/* First we check if we are on page one. If we are then we don't need a link to
the previous page or the first page so we do nothing. If we aren't then we
generate links to the first page, and to the previous page. */
if ($pagenum > 1) {
$previous = $pagenum - 1;
$paginationCtrls .= 'Previous ';
// Render clickable number links that should appear on the left of the target page number
for($i = $pagenum-4; $i < $pagenum; $i++){
if($i > 0){
$paginationCtrls .= ''.$i.' ';
}
}
}
// Render the target page number, but without it being a link
$paginationCtrls .= ''.$pagenum.' ';
// Render clickable number links that should appear on the right of the target page number
for($i = $pagenum+1; $i <= $last; $i++){
$paginationCtrls .= ''.$i.' ';
if($i >= $pagenum+4){
break;
}
}
// This does the same as above, only checking if we are on the last page, and then generating the "Next"
if ($pagenum != $last) {
$next = $pagenum + 1;
$paginationCtrls .= ' Next ';
}
}
while ($stmt->fetch()) {
"$id, $product_name, $price";
$search_output .= "
<li><div class='product'>
<a href='product.php?id=$id' class='info'>
<span class='holder'>
<img src='inventory_images/$id.jpg' alt='$product_name' />
<span class='book-name'>$product_name</span>
</a>
<a href='product.php?id=$id' class='buy-btn'>RM<span class='price'>$price</span></a>
</div>
</li>
";
}
} else {
$search_output = "<hr />0 results for <strong>$searchquery</strong><hr />";
}
} else {
$search_output = "<hr />0 results for <strong>$searchquery</strong><hr />";
}
}
?>
pass the 'searchquery' variable through from the url and get it back from the script
Learn MVC
You only pass the pagenumber to you pagination controlls, not the searchquery
Dont use $_SERVER['PHP_SELF']
Use proper escaping methods or validators instead of those preg_replaces to filter input

Having some trouble in my pagation code(PHP)

My table is posting and in that table, it shows all the posting people put in.
I am trying to make page navigation links at the bottom of the posts.
the function generateenter code here_page_links does all the work.
The code seem to be only showing the "<-" and "->" and not the link numbers. I think the function is only reading the $_GET['posting'] ==1.
(this code is from the Oreilly PHP/MySQL book. I am using it as practice)
function generate_page_links($cur_page, $num_pages) {
$page_links = '';
// If this page is not the first page, generate the "previous" link
if ($cur_page > 1) { //cur_page is just a number that is gotten from the url.
$page_links .= '<-- ';
}
else {
$page_links .= '<- ';
}
// Loop through the pages generating the page number links
for ($i = 1; $i <= $num_pages; $i++) {
if ($cur_page == $i) {
$page_links .= ' ' . $i;
}
else {
$page_links .= ' ' . $i . '';
}
}
// If this page is not the last page, generate the "next" link
if ($cur_page < $num_pages) {
$page_links .= ' ->';
}
if ($cur_page == $num_pages){ //the last page
$page_links .= ' ->';
}
return $page_links; //need to return this variable in the function
}
// Calculate pagination information
$cur_page = isset($_GET['page']) ? $_GET['page'] : 1;
$results_per_page = 3; // number of results per page
$skip = (($cur_page - 1) * $results_per_page);
$query = "SELECT * FROM posting ORDER BY date_added DESC";
$data = mysqli_query($dbc, $query);
$total = mysqli_num_rows($data);
$num_pages = ceil($total / $results_per_page);
//Query again to get just the subset of results
$query = $query . " LIMIT $skip, $results_per_page";
$result = mysqli_query($dbc, $query);
echo '<table>';
echo '<tr><td><b>Title</b></td><td><b>Date Posted</b></td></tr>';
while ($row = mysqli_fetch_array($result)) {
echo '<tr><td><a href="ad.php?
posting_id='.$row['posting_id'].'
">'.$row['title'].'</a></td>';
echo '<td>'.$row['date_added'].'</td>';
//echo '<td>'.$row['name'].'</td></tr>';
}
echo '</table>';
// Generate navigational page links if we have more than one page
if ($num_pages > 1) {
echo generate_page_links($user_search, $sort, $cur_page, $num_pages);
}
Well you have some problems here to start with:
You call the function with 4 variables
echo generate_page_links($user_search, $sort, $cur_page, $num_pages);
But the function only accepts two
function generate_page_links($cur_page, $num_pages)
If that's the code you're using, then it's probably going to crash because those variables are undefined.
Try deleting "$user_search, $sort," and see if that fixes it?

Categories