I am doing a pagination in PHP from records in Database MySQL.
I have in total 7 records to display, I have set numbers per page (resultsPerPage) as 2, so I will be displaying 4 pages.
I am displaying results from two queries:
First is table tblPaciente which shows information from my client.
Second is table tblEvolucion which shows information which I required to apply the pagination. (7 records to display)
I am displaying a query from table tblEvolucion and displaying order by clmSerie column descending.
Page 1 I want to display records with Description: "Record 7" and "Record 6"
Page 2 I want to display records with Description: "Record 5" and "Record 4"
Page 3 I want to display records with Description: "Record 3" and "Record 2"
Page 4 I want to display record with Description: "Record 1"
My problem is when I press "Previous Page", "Next Page" or any of the displaying pages (1,2,3,4), the form is being reset and is showing me nothing but the FORM (id=frmPacienteBuscar) empty, with no results. I required to display it to me next page and remains table results (id=table1) from the first query and also remain the form (id=frmPacienteBuscar).
If I search again in the form after it has been reset it will access to the page that I went before.
For example:
- First I load the page.
- Then I press page number 3
- Then everything is blank and I have to retype inputs with ids (id="searchByRut" and id="dv")
- Then I will be accessing immediately from page number 3
I have tried to pass in the HREF of my "Next Page" the variable $searchByRut, with is required for me to search in table tblPaciente and tblEvolucion but it is saying to me that is undefined index after I press a link to access any page. Here:
$outputTblEvolucion .= " <a href='{$_SERVER['PHP_SELF']}?currentPage=$prevpage'> Previous Page </a> ";
I am trying to capture it as follows at the beginning of my PHP code:
$searchByRut = $_POST["searchByRut"];
I assume that I required to pass as POST in the HREF of every link to pages the RUT but I am not able to catch it and also not sure if that is the problem.
Please let me know any clarification, thanks in advance,
testPaginization3.php
<?php
include_once('funcionesComunes.php');
require_once('mysqli_connect.php');
$outputTblEvolucion = '';
$outputTblPaciente = $outputData = '';
$searchByRut_error = '';
$searchByRut = '';
$dv_input = '';
$iCompleteFirstQuery = $iHaveToDoSecondQuery = 0;
$countDataFromTblPaciente = 0;
$searchByRut = $_POST["searchByRut"];
if(isset($_POST['searchByRut']))
{
//there are just validation if my id entered to search is valid, please ignore this part:
$error = '';
$dv = $_POST["dv"];
$dv_input = $_POST["dv"];
$searchByRut = $_POST["searchByRut"];
echo "<br>". "searchByRut={" . $searchByRut ."}";
if ($dv == "k")
$dv = "K";
$searchByRut_error = rutValidar($searchByRut, $dv, $error);
//here I am checking if any error occurred in the previous validation
if ($searchByRut_error == '')
{
$rut = $_POST['searchByRut'];
$queryDatosPaciente = mysqli_query($dbc,
"SELECT CONCAT(pa.clmNombres, ' ', pa.clmApellidos) as clmNombres
,pa.clmEmail
FROM tblPaciente pa
WHERE pa.clmRut = '$rut'
"
) or die('Error while searching!: {' . mysqli_error($dbc) . '}');
$countDataFromTblPaciente = mysqli_num_rows($queryDatosPaciente);
$iCompleteFirstQuery = 1;
}
}
//this variable iCompleteFirstQuery will tell me that I have to execute second query in detail table tblEvolucion, because I found already the main record in customer table tblPaciente
if ($iCompleteFirstQuery == 1)
{
if($countDataFromTblPaciente == 0)
{
$outputTblPaciente = 'It did not find client!';
$iHaveToDoSecondQuery = 0;
}
else
{
//Here I just build the Table with result from query of customer tblPaciente
$iHaveToDoSecondQuery = 1;
$outputTblPaciente .= "<table id='table1' border='1' align='left' cellspacing='5' cellpadding='8'>";
$outputTblPaciente .= "<tr><td align='left'><b>Name </b></td>
<td align='left'><b>Email </b></td>
</tr>";
while($row = mysqli_fetch_array($queryDatosPaciente))
{
$nombres = utf8_encode($row['clmNombres']);
$email = $row['clmEmail'];
$outputTblPaciente .= "<td align='left'> $nombres </td>
<td align='left'> $email </td>";
$outputTblPaciente .= "</tr></table><br><br><br><br><br>";
}
}
}
//In this IF condition is the part that I required to make as pagination, for the result of table tblEvolucion
if ($iHaveToDoSecondQuery == 1)
{
$sqlCount = "SELECT COUNT(*)
FROM tblEvolucion ev
WHERE ev.clmRut = '$rut'";
$resultadoQueryCount = mysqli_query($dbc,$sqlCount) or die('Error to select!: {' . mysqli_error($dbc) . '}');
$r = mysqli_fetch_row($resultadoQueryCount);
$countRecordsFound = $r[0];
echo "<br>". "countRecordsFound={" . $countRecordsFound ."}";
echo "<br><br>";
$resultsPerPage = 2;
$totalPages = ceil($countRecordsFound / $resultsPerPage);
// get the current page or set a default
if (isset($_GET['currentPage']) && is_numeric($_GET['currentPage']))
{
// cast var as int
$currentPage = (int) $_GET['currentPage'];
}
else
{
// default page num
$currentPage = 1;
}
// if current page is greater than total pages...
if ($currentPage > $totalPages)
{
// set current page to last page
$currentPage = $totalPages;
}
// if current page is less than first page...
if ($currentPage < 1)
{
// set current page to first page
$currentPage = 1;
}
// the offset of the list, based on current page
$offset = ($currentPage - 1) * $resultsPerPage;
// get the info from the db
$sqlDespliegaDatos ="SELECT ev.clmDescripcion
FROM tblEvolucion ev
WHERE ev.clmRut = '$rut'
ORDER by ev.clmSerie DESC
LIMIT $offset
,$resultsPerPage";
$resultadoQueryDespliegaDatos = mysqli_query($dbc,$sqlDespliegaDatos) or die('Error to select!: {' . mysqli_error($dbc) . '}');
$iHaveToDoSecondQuery = 1;
if($countRecordsFound == 0)
{
$outputData = 'No results from Table tblEvolucion!';
}
else
{
//From there I build the table with my records from tblEvolucion wish I required to be with pagination
$outputData = '';
$outputData .= '<table border=1 align="left" cellspacing="5" cellpadding="8">
<tr><td align="left"><b>Description </b></td>
</tr>';
while ($list = mysqli_fetch_assoc($resultadoQueryDespliegaDatos))
{
$descripcion = utf8_encode($list['clmDescripcion']);
$outputData .= '<tr>';
$outputData .= "<td align='left'><textarea id='descripcion' name='descripcion' tabindex='4' cols='50' rows='6' maxlength='1000'
value = '".$descripcion."'
readonly>".($descripcion)."</textarea>
</td>";
$outputData .= '</tr>';
}
$outputData .= '</table>';
$outputTblEvolucion = '';
/****** build the pagination links ******/
// range of num links to show
$range = 3;
// if not on page 1, don't show back links
if ($currentPage > 1)
{
// show << link to go back to page 1
$outputTblEvolucion .= " <a href='{$_SERVER['PHP_SELF']}?currentPage=1'> << </a> ";
// get previous page num
$prevpage = $currentPage - 1;
// show < link to go back to 1 page
$outputTblEvolucion .= " <a href='{$_SERVER['PHP_SELF']}?currentPage=$prevpage'> Previous Page </a> ";
}
// loop to show links to range of pages around current page
for ($x = ($currentPage - $range); $x < (($currentPage + $range) + 1); $x++)
{
// if it's a valid page number...
if (($x > 0) && ($x <= $totalPages))
{
// if we're on current page...
if ($x == $currentPage)
{
// 'highlight' it but don't make a link
$outputTblEvolucion .= " [<b>$x</b>] ";
// if not current page...
} else
{
// make it a link
$outputTblEvolucion .= " <a href='{$_SERVER['PHP_SELF']}?currentPage=$x'>$x</a> ";
}
}
}
// 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
//Here is which I think I am doing something wrong and I though to pass also my variable searchByRut but I am not able to received after pressing click on "Next Page"
$outputTblEvolucion .= " <a href='{$_SERVER['PHP_SELF']}?currentPage=$nextpage"
."&searchByRut=$searchByRut
'>Next Page</a> ";
// echo forward link for lastpage
$outputTblEvolucion .= " <a href='{$_SERVER['PHP_SELF']}?currentPage=$totalPages'>>></a> ";
} // end if
}
}
?>
<html>
<head>
<title>Pagination with Form</title>
</head>
<body>
<h1>Pagination with Form</h1>
<form id="frmPacienteBuscar" action="" method="post">
<fieldset>
<span class="error"><?= $searchByRut_error ?></span><br>
RUT: <input name="searchByRut" id="searchByRut" type="text" placeholder="Search by RUT.." tabindex="2" size="15" maxlength="8"
value="<?= $searchByRut ?>" > -
<input name="dv" id="dv" type="text" value="<?= $dv_input ?>" size="1" tabindex="2" maxlength="1"
value="<?= $dv_input ?>" > Sample: 12345678-1<br>
<button name="buscar" type="submit" id="contact-submit" data-submit="...Sending">Search</button><br>
</fieldset>
</form>
<?php
/*Here I will be printing the result of:
- the main table from tblPaciente
- the table which I required to do pagination tblEvolucion
- the links to navigate to the next and previous pages
*/
echo $outputTblPaciente;
echo "<br>";
echo $outputData;
echo "<br>";
echo $outputTblEvolucion;
?>
</body>
</html>
Thanks to the comment by #ArtisticPhoenix I will post solution with modified code:
Exactly I modify method from POST to GET and also I assined this way at the beginning of the code:
$searchByRut = isset($_POST["searchByRut"]) ? $_POST["searchByRut"] : '';
New code:
<?php
include_once('funcionesComunes.php');
require_once('mysqli_connect.php');
$outputTblEvolucion = '';
$outputTblPaciente = $outputData = '';
$searchByRut_error = '';
$searchByRut = '';
$dv_input = '';
$iCompleteFirstQuery = $iHaveToDoSecondQuery = 0;
$countDataFromTblPaciente = 0;
//$searchByRut = $_GET["searchByRut"];
$searchByRut = isset($_GET["searchByRut"]) ? $_GET["searchByRut"] : '';
$dv = isset($_GET["dv"]) ? $_GET["dv"] : '';
echo "<br>". "0searchByRut={" . $searchByRut ."}";
echo "<br>". "0dv={" . $dv ."}";
if(isset($_GET['searchByRut']))
{
//there are just validation if my id entered to search is valid, please ignore this part:
$error = '';
$dv = $_GET["dv"];
$dv_input = $_GET["dv"];
$searchByRut = $_GET["searchByRut"];
echo "<br>". "searchByRut={" . $searchByRut ."}";
if ($dv == "k")
$dv = "K";
$searchByRut_error = rutValidar($searchByRut, $dv, $error);
//here I am checking if any error ocurred in the previous validation
if ($searchByRut_error == '')
{
$rut = $_GET['searchByRut'];
$queryDatosPaciente = mysqli_query($dbc,
"SELECT CONCAT(pa.clmNombres, ' ', pa.clmApellidos) as clmNombres
,pa.clmEmail
FROM tblPaciente pa
WHERE pa.clmRut = '$rut'
"
) or die('Error while searching!: {' . mysqli_error($dbc) . '}');
$countDataFromTblPaciente = mysqli_num_rows($queryDatosPaciente);
$iCompleteFirstQuery = 1;
}
}
//this variable iCompleteFirstQuery will tell me that I have to execute second query in detail table tblEvolucion, because I found already the main record in customer table tblPaciente
if ($iCompleteFirstQuery == 1)
{
if($countDataFromTblPaciente == 0)
{
$outputTblPaciente = 'It did not find client!';
$iHaveToDoSecondQuery = 0;
}
else
{
//Here I just build the Table with result from query of customer tblPaciente
$iHaveToDoSecondQuery = 1;
$outputTblPaciente .= "<table id='table1' border='1' align='left' cellspacing='5' cellpadding='8'>";
$outputTblPaciente .= "<tr><td align='left'><b>Name </b></td>
<td align='left'><b>Email </b></td>
</tr>";
while($row = mysqli_fetch_array($queryDatosPaciente))
{
$nombres = utf8_encode($row['clmNombres']);
$email = $row['clmEmail'];
$outputTblPaciente .= "<td align='left'> $nombres </td>
<td align='left'> $email </td>";
$outputTblPaciente .= "</tr></table><br><br><br><br><br>";
}
}
}
//In this IF condition is the part that I required to make as pagination, for the result of table tblEvolucion
if ($iHaveToDoSecondQuery == 1)
{
$sqlCount = "SELECT COUNT(*)
FROM tblEvolucion ev
WHERE ev.clmRut = '$rut'";
$resultadoQueryCount = mysqli_query($dbc,$sqlCount) or die('Error to select!: {' . mysqli_error($dbc) . '}');
$r = mysqli_fetch_row($resultadoQueryCount);
$countRecordsFound = $r[0];
echo "<br>". "countRecordsFound={" . $countRecordsFound ."}";
echo "<br><br>";
$resultsPerPage = 2;
$totalPages = ceil($countRecordsFound / $resultsPerPage);
// get the current page or set a default
if (isset($_GET['currentPage']) && is_numeric($_GET['currentPage']))
{
// cast var as int
$currentPage = (int) $_GET['currentPage'];
}
else
{
// default page num
$currentPage = 1;
}
// if current page is greater than total pages...
if ($currentPage > $totalPages)
{
// set current page to last page
$currentPage = $totalPages;
}
// if current page is less than first page...
if ($currentPage < 1)
{
// set current page to first page
$currentPage = 1;
}
// the offset of the list, based on current page
$offset = ($currentPage - 1) * $resultsPerPage;
// get the info from the db
$sqlDespliegaDatos ="SELECT ev.clmDescripcion
FROM tblEvolucion ev
WHERE ev.clmRut = '$rut'
ORDER by ev.clmSerie DESC
LIMIT $offset
,$resultsPerPage";
$resultadoQueryDespliegaDatos = mysqli_query($dbc,$sqlDespliegaDatos) or die('Error to select!: {' . mysqli_error($dbc) . '}');
$iHaveToDoSecondQuery = 1;
if($countRecordsFound == 0)
{
$outputData = 'No reults from Table tblEvolucion!';
}
else
{
//From there I build the table with my records from tblEvolucion wish I required to be with pagination
$outputData = '';
$outputData .= '<table border=1 align="left" cellspacing="5" cellpadding="8">
<tr><td align="left"><b>Description </b></td>
</tr>';
while ($list = mysqli_fetch_assoc($resultadoQueryDespliegaDatos))
{
$descripcion = utf8_encode($list['clmDescripcion']);
$outputData .= '<tr>';
$outputData .= "<td align='left'><textarea id='descripcion' name='descripcion' tabindex='4' cols='50' rows='6' maxlength='1000'
value = '".$descripcion."'
readonly>".($descripcion)."</textarea>
</td>";
$outputData .= '</tr>';
}
$outputData .= '</table>';
$outputTblEvolucion = '';
/****** build the pagination links ******/
// range of num links to show
$range = 3;
// if not on page 1, don't show back links
if ($currentPage > 1)
{
// show << link to go back to page 1
//$outputTblEvolucion .= " <a href='{$_SERVER['PHP_SELF']}?currentPage=1'> << </a> ";
$outputTblEvolucion .= " <a href='{$_SERVER['PHP_SELF']}?currentPage=1"
."&searchByRut=$searchByRut"
."&dv=$dv
'>First Page</a> ";
// get previous page num
$prevpage = $currentPage - 1;
// show < link to go back to 1 page
//$outputTblEvolucion .= " <a href='{$_SERVER['PHP_SELF']}?currentPage=$prevpage'> Previous Page+ </a> ";
$outputTblEvolucion .= " <a href='{$_SERVER['PHP_SELF']}?currentPage=$prevpage"
."&searchByRut=$searchByRut"
."&dv=$dv
'>Previous Page+ </a> ";
}
// loop to show links to range of pages around current page
for ($x = ($currentPage - $range); $x < (($currentPage + $range) + 1); $x++)
{
// if it's a valid page number...
if (($x > 0) && ($x <= $totalPages))
{
// if we're on current page...
if ($x == $currentPage)
{
// 'highlight' it but don't make a link
$outputTblEvolucion .= " [<b>$x</b>] ";
// if not current page...
} else
{
// make it a link
//$outputTblEvolucion .= " <a href='{$_SERVER['PHP_SELF']}?currentPage=$x'>$x</a> ";
//ERROR
$outputTblEvolucion .= " <a href='{$_SERVER['PHP_SELF']}?currentPage=$x"
."&searchByRut=$searchByRut"
."&dv=$dv
'>$x</a> ";
}
}
}
// 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
//Here is wich I think I am doing something wrong and I though to pass also my variable searchByRut but I am not able to received after pressing click on "Next Page"
$outputTblEvolucion .= " <a href='{$_SERVER['PHP_SELF']}?currentPage=$nextpage"
."&searchByRut=$searchByRut"
."&dv=$dv
'>Next Page</a> ";
// echo forward link for lastpage
$outputTblEvolucion .= " <a href='{$_SERVER['PHP_SELF']}?currentPage=$totalPages"
."&searchByRut=$searchByRut"
."&dv=$dv
'>Last Page</a> ";
} // end if
}
}
?>
<html>
<head>
<title>Pagination with Form</title>
</head>
<body>
<h1>Pagination with Form</h1>
<form id="frmPacienteBuscar" action="" method="get">
<fieldset>
<span class="error"><?= $searchByRut_error ?></span><br>
RUT: <input name="searchByRut" id="searchByRut" type="text" placeholder="Search by RUT.." tabindex="2" size="15" maxlength="8"
value="<?= $searchByRut ?>" > -
<input name="dv" id="dv" type="text" value="<?= $dv_input ?>" size="1" tabindex="2" maxlength="1"
value="<?= $dv_input ?>" > Sample: 12345678-1<br>
<button name="buscar" type="submit" id="contact-submit" data-submit="...Sending">Search</button><br>
</fieldset>
</form>
<?php
/*Here I will be printing the result of:
- the main table from tblPaciente
- the table which I required to do pagination tblEvolucion
- the links to navigate to the next and previous pages
*/
echo $outputTblPaciente;
echo "<br>";
echo $outputData;
echo "<br>";
echo $outputTblEvolucion;
?>
</body>
</html>
Related
I'm trying to create pagination in PHP where 5 pages are displayed.
When on the first page we have:
[1][2][3][4][5] ...[325][>>]
Clicking on [325] will take you to that page (the last record), clicking on the right arrow will take you to page [2].
When on the second page we have:
[<<][1]...[2][3][4][5][6] ...[325][>>]
And when on the last page we have:
[<<][1]...[321][322][323][324][325]
I've been researching on how to do this without much luck. I think I understand that I need to create an array with adjacent pages of 2 on each side of the active page, when we are on any page except the first or last page. I also need to create an <li>1</li>
and
<li><?php echo $last_record; ?></li>
for when a user is anywhere but the first or last record.
I have the following code which works great, however when we start getting a large number of records, the pagination count gets ridiculous.
<ul class="pagination pull-left pagination-md">
<?php
// Creates back button in pagination
if(isset($page)) {
if($page > 1) {
$page_minus = $page-1;
echo "<li><a href='blog.php?page=$page_minus'> « </a></li>";
}
}
?>
<?php
global $con;
$q_pagination = mysqli_prepare($con, "SELECT COUNT(*) FROM admin_panel WHERE ");
$q_pagination->execute();
$result_pagination = $q_pagination->get_result();
$rows_result = $result_pagination->fetch_array();
$total_rows = array_shift($rows_result);
$post_per_page = $total_rows/15;
$post_per_page = ceil($post_per_page);
for($i = 1; $i <= $post_per_page; $i++) {
if(isset($page)){
if($i == $page) {
echo "<li class='active'><a href='blog.php?page=$i'>$i</a></li>";
}
else {
echo "<li><a href='blog.php?page=$i'>$i</a></li>";
}
}
}
// Creates the forward button in pagination
if(isset($page)){
if($page+1 <= $post_per_page) {
$page_plus = $page+1;
echo "<li><a href='blog.php?page=$page_plus'> » </a></li>";
}
}
?>
</ul>
I'll admit, after researching and attempting to make this work I'm just getting twisted in the logic. Does anyone have any thoughts on how to best approach this? Leads, current examples, etc. Most of what I've found is dated, incomplete, or stupid long.
<?php
session_start();
include "mysqli_connect.php";
$companyID = $_SESSION['compid'];
$db = new Database();
$dbc = $db->getConnection();
$display = 3; //number of records per page
$pages;
$dbb = new Database();
$dbcb = $dbb->getConnection();
$stat = "select * from reservationStatus where resStatId = '$companyID' ";
$r = mysqli_query($dbcb, $stat);
//variable for sorting - default is for registration date
$sort = (isset($_GET['sort'])) ? $_GET['sort'] : 'rd';
switch ($sort)
{
case 'ln':
$orderby = 'uniquenumber ASC';
break;
case 'fn':
$orderby = 'status ASC';
break;
case 'rd':
$orderby = 'resId ASC';
break;
case 'em' :
$orderby = 'resDate ASC';
break;
default:
$orderby = 'resId ASC';
break;
}
if(isset($_GET['p']) ) //already calculated
{
$pages=$_GET['p'];
}
else
{
//get the total number of records from the table
$q = "select count(resId) from reservation where companyID = '$companyID'";
$r = mysqli_query($dbc, $q);
$row = mysqli_fetch_array($r, MYSQLI_NUM);
$records=$row[0];
if($records > $display ) //$display is the number of records per page
//ceil rounds fractions up to integer value
$pages=ceil($records/$display);
else
$pages = 1;
}
//now determine where in the database to start
if(isset($_GET['s']) ) //already calculated
$start=$_GET['s'];
else
$start = 0;
//$q = "select * from users LIMIT $start, $display";
$q = "select * from reservation where companyID = '$companyID' order by $orderby LIMIT $start, $display";
$r = mysqli_query($dbc, $q);
if($r)
{
echo '<br />';
//display a table of results
echo '<div class="container">';
echo '<h1> Your Orders </h1>';
echo '<table align="center" class="table table-bordered table-striped" width="60%">';
echo '<tr bgcolor="#87CEEB">
<td><b>View</b></td>
<td><b>Change Status</b></td>
<td><b> Reference Number</b></td>
<td><b>Status</b></td>
<td><b>Date</b></td>
<td><b>Total Price</b></td></tr>';
//above is the header
//loop below adds the user details
//use the following to set alternate backgrounds
$bg = '#eeeeee';
while($row = mysqli_fetch_array($r))
{
$stat = "select * from reservationStatus where resStatusId = $row[7] ";
$rr = mysqli_query($dbcb, $stat);
$roww = mysqli_fetch_array($rr);
$bg = ($bg=='#eeeeee' ? '#ffffff' : '#eeeeee');
echo '<tr bgcolor="' . $bg. '">
<td>View</td>
<td>Change Status </td>
<td>'.$row[2].'</td>
<td>'.$roww[1].'</td>
<td>'.$row[1]. ' ' . $row[8].'</td>
<td>'.$row[3].'</td>
</tr>';
}
echo '</table></div>';
}
else
{
echo '<p class="error">' . $q . '</p>';
echo '<p class="error"> Oh dear. There was an error</p>';
echo '<p class="error">' . mysqli_error($dbc) .'</p>';
}
mysqli_free_result($r);
//makes links to other pages if required
if($pages > 1)
{
echo '<br /><p> ' ;
//find out what page we are on
$currentpage = ($start/$display)+1;
//need a previous button if not first page
if($currentpage != 1)
{
echo ' <a href="viewOrdersForCompanies.php?$s=' . ($start - $display) .
'&p=' .$pages . '&sort='.$sort.'"> Previous </a>';
}
//create the numbered pages
for($i = 1; $i <= $pages; $i++)
{
if($i != $currentpage)
{
//the 's' paramater is used in the link to determine which the value
// in the LIMIT clause used in the select statement near the top of the page
echo '<a href="viewOrdersForCompanies.php?s=' . (($display * ($i-1))) . '&p='
. $pages . '&sort='.$sort.'"> ' . $i . ' </a>';
}
//  is a character to insert a whitespace
}
//if not last page create next button
if($currentpage != $pages)
{
echo '<a href="viewOrdersForCompanies.php?s=' . ($start+$display) . '&p=' . $pages
. '&sort='.$sort.'"> Next </a>';
}
echo '</p>';
}
?>
Hello guys I'm having trouble with this script I made. Any time I use the search bar to search for data on my website in a table form the first row always come back perfectly with the data in tact but any thing after the first row all the data falls out of place in the other rows. I was able to do this perfectly in non-table structure situations so I don't know why this is doing this I need help how I can keep all the data intact.
Screen Shot
<?php
//SEARCHX
include("hidden_path/mysqli/procedural/session/session_crud/v1/0/instructions/php/session_and_connection.php");
$output = ' ';
if(isset($_GET['search']) && $_GET['search'] !== ' ') {
$user_input = $_GET['search'];
if ($user_input === "") {
header('Location: '.$_SERVER['PHP_SELF']);
die;
}
//PAGINATION
$user_input = $_GET['search'];
$and = "&";
$pagevx = "page=";
//SEARCHX
$user_input = trim(" $user_input ");
$user_input = preg_replace('/\s+/', ' ', $user_input);
$user_input = mysqli_real_escape_string($connect, $user_input);
$user_input = htmlspecialchars($user_input);
//PAGINATION
$page = mysqli_query($connect, "SELECT COUNT(*) FROM posts WHERE post_title LIKE '%$user_input%' OR post_content LIKE '%$user_input%'");
// total row count
$row = mysqli_fetch_row($page);
$rows = $row[0];
// results displayed per page
$page_rows = 2;
// page number of last page
$last = ceil($rows/$page_rows);
// makes sure $last cannot be less than 1
if($last < 1) {
$last = 1;
}
// page num
$pagenum = 1;
// get pagenum from URL if it is present otherwise it is 1
if(isset($_GET['page'])) {
$pagenum = preg_replace('#[^0-9]#', '', $_GET['page']);
}
// makes sure the page number isn't below 1, or more then our $last page
if($pagenum < 1) {
$pagenum = 1;
}
else if($pagenum > $last) {
$pagenum = $last;
}
// set the rage of rows to query for the chosen $pagenum
$limit = 'LIMIT ' . ($pagenum - 1) * $page_rows . ',' . $page_rows;
$page = mysqli_query($connect, "SELECT * FROM posts WHERE post_title LIKE '%$user_input%' OR post_content LIKE '%$user_input%' ORDER BY post_id DESC $limit");
// establish $paginationCtrls variable
$paginationCtrls = '';
// if more the 1 page
if($last != 1) {
if($pagenum > 1) {
$previous = $pagenum - 1;
$paginationCtrls .= '<span class="pag_back_arrow"; style="text-decoration: none;"><</span> ';
// Render clickable number links
for($i = $pagenum - 4; $i < $pagenum; $i++) {
if($i > 0) {
$paginationCtrls .= ''.$i.' ';
}
}
}
// render the target page number without a link
$paginationCtrls .= ''. $pagenum . ' ';
// render clickable number links that appear on the right
for($i = $pagenum + 1; $i < $last; $i++) {
$paginationCtrls .= ''.$i.' ';
// allows up to 4 pages
if($i >= $pagenum + 4) {
break;
}
}
if($pagenum != $last) {
$next = $pagenum + 1;
$paginationCtrls .= ' <span class="pag_next_arrow"; style="text-decoration: none;">></span> ';
}
}
//SEARCHX
?>
<!DOCTYPE html>
<html>
<head>
<title>
Results
</title>
</head>
<meta name="viewport" content="width=device-width">
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="0/instructions/css/query/desktop.css">
<link rel="stylesheet" type="text/css" href="0/instructions/css/query/mobile.css">
<body>
<?php
//SEARCHX
$c = mysqli_num_rows($page);
if($c == 0) {
$output = '<h2 class="no_results_error_message";><span style="color: red;">No results for: </span><b><span style="color: white;">' . $user_input . '</span></h2></b>';
} else {
?>
<div class="result_section";>
<h2><span class="for_headline">Results For: </span><span id="result_output"><?php $outputx = "$user_input"; print("$outputx"); ?></span></h2>
</div>
<!-- Search Box -->
<?php include("search_box.php"); ?> <br>
<table width='80%' border=0>
<tr bgcolor='#CCCCCC'>
<td>user_id</td>
<td>topic_id</td>
<td>post_title</td>
<td>post_content</td>
<td>post_date</td>
<td>Update</td>
</tr>
<?php
// shows the user what page they are on, and the total number of pages
$textline1 = "Search_i";
$textline2 = "Page <b>$pagenum</b> of <b>$last</b>";
while($row = mysqli_fetch_array($page, MYSQLI_ASSOC)) {
echo "<tr>";
echo "<td>".$row['user_id']."</td>";
echo "<td>".$row['topic_id']."</td>";
echo "<td>".$row['post_title']."</td>";
echo "<td>".$row['post_content']."</td>";
echo "<td>".$row['post_date']."</td>";
echo "<td>Edit | Delete</td></table>";
?>
<?php
$output .= '<a href="' . $link . '">
</a>';
}
}
} else {
header("location: ./");
}
print("$output");
mysqli_close($connect);
?>
<!-- PAGINATION -->
<!--shows the user what page they are on, and the total number of pages -->
<p><?php //echo $textline1 = "Search_i"; ?></p>
<p id="page_of";><?php //echo $textline2; ?></p>
<div class="pagination_controls"><?php echo $paginationCtrls; ?></div>
</body>
</html>
you are closing table in loop. Change your code with
while ($row = mysqli_fetch_array($page, MYSQLI_ASSOC)) {
echo "<tr>";
echo "<td>" . $row['user_id'] . "</td>";
echo "<td>" . $row['topic_id'] . "</td>";
echo "<td>" . $row['post_title'] . "</td>";
echo "<td>" . $row['post_content'] . "</td>";
echo "<td>" . $row['post_date'] . "</td>";
echo "<td>Edit | Delete</td></tr>";
}
</table> //close table after loop
I am trying to store values from form radio to array. But problem which i am facing is that every time array 1st index is replaced with new value. I believe this is scope problem. I also tried to declare global array but no success.
Here is the code:
<?php
include_once("connection.php");
$c = new DBcon();
$c->startcon();
global $array; // not effecive
// $q = $_POST['t'];
// echo 'fff', $q;
$page = $_GET['page'];
echo 'pagesss', $page, 'ppp';
if ($page == "") {
$page = "1";
} else {
// If page is set, let's get it
$page = $_GET['page'];
}
// Now lets get all messages from your database
$sql = "SELECT * FROM quizes";
$query = mysql_query($sql);
// Lets count all messages
$num = mysql_num_rows($query);
// Lets set how many messages we want to display
$per_page = "2";
// Now we must calculate the last page
$last_page = $num;
echo 's', $num;
// And set the first page
$first_page = "1";
// Here we are making the "First page" link
echo "<a href='?page=" . $first_page . "'>First page</a> ";
// If page is 1 then remove link from "Previous" word
if ($page == $first_page) {
echo "Previous ";
} else {
if (!isset($page)) {
echo "Previous ";
} else {
// But if page is set and it's not 1.. Lets add link to previous word to take us back by one page
$previous = $page - 1;
echo "<a href='?page=" . $previous . "'>Previous</a> ";
}
}
// If the page is last page.. lets remove "Next" link
if ($page == $last_page) {
echo "Next ";
} else {
// If page is not set or it is set and it's not the last page.. lets add link to this word so we can go to the next page
if (!isset($page)) {
$next = $first_page + 1;
echo "<a href='?page=" . $next . "'>Next</a> ";
} else {
$next = $page + 1;
echo "<a href='?page=" . $next . "'>Next</a> ";
}
}
// And now lets add the "Last page" link
echo "<a href='?page=" . $last_page . "'>Last page</a>";
// Math.. It gets us the start number of message that will be displayed
$start = ($page * ($page - 1)) / $page;
echo 'start', $start;
echo 'page', $page;
// Now lets set the limit for our query
$limit = "LIMIT $start, $per_page";
// It's time for getting our messages
$sql = "SELECT * FROM quizes $limit";
$query = mysql_query($sql);
echo "<br /><br />";
// And lets display our messages
$i = 0;
$l = 0;
while ($row = mysql_fetch_array($query) or die(mysql_error())) {
$a = $row['A'];
echo '<form method="get" action="?page=".$next."">';
while ($row = mysql_fetch_array($query)) {
echo '<div class="boxed" >';
echo "\t" . '<tr><th>' .
$row['question'] . "<br>" .
'</th><th>' . "<input type='radio' name= 't[]' value='{$row['A']}'>" . $row['A'] . "<br>" .
'</th><th>' . "<input type='radio' name='t[]' value='{$row['B']}'>" . $row['B'] . "<br>" .
'</th><th>' . "<input type='radio' name='t[]' value='{$row['C']}'>" . $row['C'] . "<br>" .
'</th><th>' . "<input type='radio' name='t[]' value='{$row['D']}'>" . $row['D'] . '</th>
</tr>';
echo '<input type="hidden" name="page" value="' . $next . '">';
echo '<input type="submit" name="submit"/>';
$i++;
echo '</div>';
echo '</div>';
}
echo '</form>';
if (isset($_GET['submit'])) {
$example = $_GET['t'];
foreach ($example as $value) {
$array[$i++] = ($value);
echo "$array[0] <br>"; // printing correct statement but replacing old values with new value everytime.
echo "$array[1] <br>"; // 0 values
echo "$array[2] <br>"; // 0 values
}
}
}
?>
I have seen these posts: PHP array indexing: $array[$index] vs $array["$index"] vs $array["{$index}"] , PHP - define static array of objects but no help. Kindly help what should i do?
You cannot do
$array[$i++]
this will always be $array[1]
instead do
$i++;
$array[$i]= $value;
P.S. $array is a terrible name for a variable...
if (isset($_GET['submit'])) {
$example = $_GET['t'];
$i=0;
$arrayA = array();
foreach ($example as $value) {
$arrayA[$i] = ($value);
$i++;
}
print_r($arrayA);
}
if you do
$array[$i++] ;
it wont work , just try this and it wont replace your old value
$array[$i] = $value;
$i++;
You must increment your variable first, then use the variable as the array key.
Edit: this is what you're looking for:
$i = 0;
foreach ($example as $value) {
$array[$i] = $value;
$i++;
}
I have written this code for a search page in PHP and I would like to know a way to make the search results more accurate. Some search strings will pull up everything in the database because it contains that word. Here is my code
<?php include("header.php");?>
<h3>Rental Search Results</h3>
<div class="searchbox">
<form method="get" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<label for="usersearch">Search Rentals Now:</label>
<input type="text" name="usersearch" value="<?php echo $_GET['usersearch']; ?>" />
<input type="submit" name="submit" value="Search" />
</form>
</div>
<br />
<br />
<?php
// This function builds a search query from the search keywords and sort setting
function build_query($user_search, $sort) {
$search_query = "SELECT * FROM online_rental_db";
// Extract the search keywords into an array
$clean_search = str_replace(',', ' ', $user_search);
$search_words = explode(' ', $clean_search);
$final_search_words = array();
if (count($search_words) > 0) {
foreach ($search_words as $word) {
if (!empty($word)) {
$final_search_words[] = $word;
}
}
}
// Generate a WHERE clause using all of the search keywords
$where_list = array();
if (count($final_search_words) > 0) {
foreach($final_search_words as $word) {
$where_list[] = "Description LIKE '%$word%' OR Manufacturer LIKE '%$word%' OR Model LIKE '%$word%' OR Category LIKE '%$word%'";
}
}
$where_clause = implode(' OR ', $where_list);
// Add the keyword WHERE clause to the search query
if (!empty($where_clause)) {
$search_query .= " WHERE $where_clause";
}
// Sort the search query using the sort setting
switch ($sort) {
// Ascending by job title
case 1:
$search_query .= " ORDER BY Description";
break;
// Descending by job title
case 2:
$search_query .= " ORDER BY Description DESC";
break;
// Ascending by state
case 3:
$search_query .= " ORDER BY Manufacturer";
break;
// Descending by state
case 4:
$search_query .= " ORDER BY Manufacturer DESC";
break;
// Ascending by date posted (oldest first)
case 5:
$search_query .= " ORDER BY Model";
break;
// Descending by date posted (newest first)
case 6:
$search_query .= " ORDER BY Model DESC";
break;
default:
// No sort setting provided, so don't sort the query
}
return $search_query;
}
// This function builds navigational page links based on the current page and the number of pages
function generate_page_links($user_search, $sort, $cur_page, $num_pages) {
$page_links = '';
// If this page is not the first page, generate the "previous" link
if ($cur_page > 1) {
$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 .= ' ->';
}
else {
$page_links .= ' ->';
}
return $page_links;
}
// Grab the sort setting and search keywords from the URL using GET
$user_search = $_GET['usersearch'];
// Calculate pagination information
$cur_page = isset($_GET['page']) ? $_GET['page'] : 1;
$results_per_page = 5; // number of results per page
$skip = (($cur_page - 1) * $results_per_page);
// Start generating the table of results
echo '<table class="results">';
echo '<td align="center">Description</td><td align="center">Manufacturer</td><td align="center">Model #</td><td align="center">Image</td>';
// Generate the search result headings
echo '<tr class="bottomborder">';
echo '</tr>';
// Connect to the database
require_once('connectvars.php');
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
// Query to get the total results
$query = build_query($user_search,'');
$result = mysqli_query($dbc, $query);
$total = mysqli_num_rows($result);
$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);
while ($row = mysqli_fetch_array($result)) {
$description = $row['Description'];
$model = $row['Model'];
$manufacturer = $row['Manufacturer'];
$image = $row['Image'];
$hour = $row['Hour'];
$day = $row['Day'];
$week = $row['Week'];
$month = $row['Month'];
$file = $row['PDF'];
$ID = $row['ID'];
$Category = $row['Category'];
$CTGID = $row['CTGID'];
if ($image == "") {
$image = "No Image";
}else {
$image = "<a class=\"thumbnail\" href=\"pp.php?ID=$ID\"><img class=\"rental_image\" src=\"$image\"><span><img src=\"$image\" ><br> $description</span></a>";
}
echo '<tr>';
echo "<td align=\"center\" valign=\"middle\" width=\"25%\">$description</td>";
echo "<td align=\"center\" valign=\"middle\" width=\"25%\">$manufacturer</td>";
echo "<td align=\"center\" valign=\"middle\" width=\"25%\">$model</td>";
echo "<td align=\"center\" valign=\"middle\" width=\"25%\">$image</td>";
echo '</tr>';
}
echo '</table>';
// Generate navigational page links if we have more than one page
if ($num_pages > 1) {
echo generate_page_links($user_search, '', $cur_page, $num_pages);
}
mysqli_close($dbc);
?>
<?php include("footer.php");?>
</div>
</body>
</html>
I would use a fulltext index with match against.
Kindly use the AND not OR. Example
Searching 4 word:
Hello, How, are, you
With OR it looks like:
like '%Hello%' or .. like '%How%' or .. like '%are%' or ... '%you%'
Now want would happen in a row any of the four words found it is selected and displayed.
With AND it looks like:
like '%Hello%' and .. like '%How%' and .. like '%are%' and ... '%you%'
Now only the row which has the four words would be only selected.
Your can also say that in any row as Apples or Oranges would be selected,
In AND Apples and Oranges means only having both things is required.
Right now, all my images are basically inserted onto my page at the same time (or so it appears). How can I create an order, so my images appear one being one left, left to right, top to bottom?
I'm using MySQL to store the image name by the way. So maybe I should create an order by ascending ID for which the image name is processed onto my php? I don't know, any recommendations would be appreciated.
This is a small bit of the code to illustrate what I mean. It's the image code being looped:
echo '<img src="https://s3.amazonaws.com/pictures/' . $objResult["Image"] . '.png" />
EDIT:
Here's the code for more context:
<html>
<body>
<?php
$objConnect = mysql_connect("localhost","root","") or die(mysql_error());
$objDB = mysql_select_db("dfvdfv");
$strSQL = "SELECT * FROM images";
if (!isset($_GET['Page'])) $_GET['Page']='0';
$objQuery = mysql_query($strSQL);
$Num_Rows = mysql_num_rows($objQuery);
$Per_Page = 16; // Per Page
$Page = $_GET["Page"];
if(!$_GET["Page"])
{
$Page=1;
}
$Prev_Page = $Page-1;
$Next_Page = $Page+1;
$Page_Start = (($Per_Page*$Page)-$Per_Page);
if($Num_Rows<=$Per_Page)
{
$Num_Pages =1;
}
else if(($Num_Rows % $Per_Page)==0)
{
$Num_Pages =($Num_Rows/$Per_Page) ;
}
else
{
$Num_Pages =($Num_Rows/$Per_Page)+1;
$Num_Pages = (int)$Num_Pages;
}
$strSQL .=" order by ImagesID ASC LIMIT $Page_Start , $Per_Page";
$objQuery = mysql_query($strSQL);
$cell = 0;
echo '<table border="1" cellpadding="2" cellspacing="1"><tr>';
while($objResult = mysql_fetch_array($objQuery))
{
if($cell % 4 == 0) {
echo '</tr><tr>';
}
if($cell == 2) {
echo '<td>RESERVED</td>';
} elseif ($cell == 3) {
echo '<td>The other cell</td>';
} else {
echo '
<td><img src="https://s3.amazonaws.com/images/' . $objResult["Image"] . '" />' .
$objResult["ImagesName"] . '</td>'; }
$cell++;
}
echo '</tr></table>';
?>
<br />
view more:
<?php
if($Prev_Page)
{
echo " <a href='$_SERVER[SCRIPT_NAME]?Page=$Prev_Page'>prev</a> ";
}
{
echo "|";
}
if($Page!=$Num_Pages)
{
echo " <a href ='$_SERVER[SCRIPT_NAME]?Page=$Next_Page'>next</a> ";
}
?>
<?php
mysql_close($objConnect);
?>
</body>
</html>
Assuming your iterating through a single loop to write your html and therefor the images it could be easily done by setting the css float attribute to left, put the images in a div container with a size of your choice, so the images row will break if they reach the right border. This will lead to building up the images from left to right.
A code example with your snippet embedded:
// open container
echo '<div style="width:\'500px\'">';
foreach ($results as $key => $objResult) {
echo '<img style="float:left;" src="https://s3.amazonaws.com/pictures/' . $objResult["Picture"] . '.png" />';
}
// close container
echo '</div>';
I suggest using stylesheet instead of setting the style attribute directly but for simplicity of the example it's just this way.
example for second question in comments
if ($objResult["description"]) {
$imageTitle = $objResult["description"];
} else {
$imageTitle = $objResult["number"];
}
echo
'<td>'.
'<img src="https://s3.amazonaws.com/images/' . $objResult["Image"] . '" />' .
$imageTitle .
'</td>';
If you want to change the order in which images appear, add a sort_order column to your database and put an index on it. When you add pictures, increment the sort_order. I prefer to increment by 10 so I have room to move images in-between others.
When you select from the database make sure you ORDER BY sort_order.