pagination always showing page first - php

hy, i have a problem to set the pagination using PHP and oracle database, the page only show the first page value. when i click button next, the page change from page 1 to page 2, page 3, etc, but the value still same with page 1. i dont know and i dont have any idea to fix this error..
here is my code for set up record set ..
<?php
// Set up recordset
define("ewSqlSelectCount", "SELECT count(*) count FROM sid_mst_dealer", true);
$sSql_count = BuildSqlang(ewSqlSelectCount, ewSqlWhere, ewSqlGroupBy, ewSqlHaving, ewSqlOrderBy, $sDbWhere, $sOrderBy);
//echo "$sSql_count" . "<br/ >";
$rs_count = moi_query($sSql_count , $conn) or die("Failed to execute query at line " . __LINE__ . ": " . moi_error($conn) . '<br>SQL: ' . $sSql);
//echo $rs_count;
oci_execute($rs_count);
$nTotalRecs = oci_fetch_array($rs_count);
$nTotalRecs = $nTotalRecs['COUNT'];
$rs = moi_query($sSql, $conn) or die("Failed to execute query at line " . __LINE__ . ": " . moi_error($conn) . '<br>SQL: ' . $sSql);
//echo $rs;
oci_execute($rs);
if ($nDisplayRecs <= 0) { // Display all records
$nDisplayRecs = $nTotalRecs;
}
$nStartRec = 1;
SetUpStartRec(); // Set up start record position
?>
this is the function..
function SetUpStartRec()
{
// Check for a START parameter
global $nStartRec;
global $nDisplayRecs;
global $nTotalRecs;
if (strlen($_GET[ewTblStartRec]) > 0)
{
$nStartRec = $_GET[ewTblStartRec];
$_SESSION[ewSessionTblStartRec] = $nStartRec;
} elseif (strlen($_GET["pageno"]) > 0)
{
$nPageNo = $_GET["pageno"];
if (is_numeric($nPageNo))
{
$nStartRec = ($nPageNo-1)*$nDisplayRecs+1;
if ($nStartRec <= 0)
{
// echo 'jangan ke sini';
$nStartRec = 1;
}
elseif ($nStartRec >= (($nTotalRecs-1)/$nDisplayRecs)*$nDisplayRecs+1)
{
$nStartRec = (($nTotalRecs-1)/$nDisplayRecs)*$nDisplayRecs+1;
}
$_SESSION[ewSessionTblStartRec] = $nStartRec;
}
else
{
$nStartRec = $_SESSION[ewSessionTblStartRec];
if (!(is_numeric($nStartRec)) || ($nStartRec == ""))
{
$nStartRec = 1; // Reset start record counter
$_SESSION[ewSessionTblStartRec] = $nStartRec;
}
}
}
else
{
$nStartRec = #$_SESSION[ewSessionTblStartRec];
if (!(is_numeric($nStartRec)) || ($nStartRec == "")) {
$nStartRec = 1; // Reset start record counter
$_SESSION[ewSessionTblStartRec] = $nStartRec;
}
}
}
and here is the query
<?php
define("ewTblVar", "sid_mst_dealer", true);
define("ewTblRecPerPage", "RecPerPage", true);
define("ewSessionTblRecPerPage", "sid_mst_dealer_RecPerPage", true);
define("ewTblStartRec", "start", true);
define("ewSessionTblStartRec", "sid_mst_dealer_start", true);
define("ewTblShowMaster", "showmaster", true);
define("ewSessionTblMasterKey", "sid_mst_dealer_MasterKey", true);
define("ewSessionTblMasterWhere", "sid_mst_dealer_MasterWhere", true);
define("ewSessionTblDetailWhere", "sid_mst_dealer_DetailWhere", true);
define("ewSessionTblAdvSrch", "sid_mst_dealer_AdvSrch", true);
define("ewTblBasicSrch", "psearch", true);
define("ewSessionTblBasicSrch", "sid_mst_dealer_psearch", true);
define("ewTblBasicSrchType", "psearchtype", true);
define("ewSessionTblBasicSrchType", "sid_mst_dealer_psearchtype", true);
define("ewSessionTblSearchWhere", "sid_mst_dealer_SearchWhere", true);
define("ewSessionTblSort", "sid_mst_dealer_Sort", true);
define("ewSessionTblOrderBy", "sid_mst_dealer_OrderBy", true);
define("ewSessionTblKey", "sid_mst_dealer_Key", true);
// Table level SQL
define("ewSqlSelect", "SELECT * FROM sid_mst_dealer", true);
if($_REQUEST[dealer_id]==""){
if($_REQUEST[x_status]!=""){
define("ewSqlWhere", " active_flag ='".$_REQUEST[x_status]."'", true);
}else{
define("ewSqlWhere", "active_flag='0'", true);
}
}else{
define("ewSqlWhere", "", true);
}
define("ewSqlGroupBy", "", true);
define("ewSqlHaving", "", true);
define("ewSqlOrderBy", "", true);
define("ewSqlOrderBySessions", "", true);
define("ewSqlKeyWhere", "dealer_id = '#dealer_id'", true);
define("ewSqlUserIDFilter", "", true);
?>
i really need help to fix this.. thank u :D

I think the problem is the lack of a limit within that obscure sql which is the key piece to the puzzle in terms of pagination. If you consider the following:
select * from `users` where `name`='fred' limit 0,10;
That would show the first 10 records where the user is called "Fred" and then
select * from `users` where `name`='fred' limit 10,10;
The second statement would show the next 10 records where the user is called "Fred"
I simply don't understand your methodology in constructing the sql but IMO you need to add a limit - and the logic associated to calculate which page in the recordset you are on so that you can add next/previous links.

here is the pagination..
<table border="0" cellspacing="0" cellpadding="0">
<tr>
<td><span >Page </span> </td>
<!--first page button-->
<?php if ($nStartRec == 1) { ?>
<td><img src="images/firstdisab.gif" alt="First" width="16" height="16" border="0"> </td>
<?php } else { ?>
<td><img src="images/first.gif" alt="First" width="16" height="16" border="0"> </td>
<?php } ?>
<!--previous page button-->
<?php if ($PrevStart == $nStartRec) { ?>
<td><img src="images/prevdisab.gif" alt="Previous" width="16" height="16" border="0"> </td>
<?php } else { ?>
<td><img src="images/prev.gif" alt="Previous" width="16" height="16" border="0"> </td>
<?php } ?>
<!--current page number-->
<td><input type="text" name="pageno" value="<?php echo intval(($nStartRec-1)/$nDisplayRecs+1); ?>" size="4"> </td>
<!--next page button-->
<?php if ($NextStart == $nStartRec) { ?>
<td><img src="images/nextdisab.gif" alt="Next" width="16" height="16" border="0"> </td>
<?php } else { ?>
<td><img src="images/next.gif" alt="Next" width="16" height="16" border="0"> </td>
<?php } ?>
<!--last page button-->
<?php if ($LastStart == $nStartRec) { ?>
<td><img src="images/lastdisab.gif" alt="Last" width="16" height="16" border="0"> </td>
<?php } else { ?>
<td><img src="images/last.gif" alt="Last" width="16" height="16" border="0"> </td>
<?php } ?>
<td><span > of <?php echo intval(($nTotalRecs-1)/$nDisplayRecs+1);?></span> </td>
</tr>
</table>
<?php if ($nStartRec > $nTotalRecs) { $nStartRec = $nTotalRecs; }
$nStopRec = $nStartRec + $nDisplayRecs - 1;
$nRecCount = $nTotalRecs - 1;
if ($rsEof) { $nRecCount = $nTotalRecs; }
if ($nStopRec > $nRecCount) { $nStopRec = $nRecCount; } ?>
<span >Records <?php echo $nStartRec; ?> to <?php echo $nStopRec; ?> of <?php echo $nTotalRecs; ?></span>
<?php } else { ?>
<?php if ($sSrchWhere == "0=101") {?>
<span ></span>
<?php } else { ?>
<span >No records found</span>
<?php } ?>
<?php } ?> </td>
</tr>
</table>

As stated by #RamRaider your methodology for pagination is somewhat vague.
As of Oracle 12c, you could use the following example query to implement pagination.
SELECT fieldA,fieldB
FROM table
ORDER BY fieldA
OFFSET 5 ROWS FETCH NEXT 14 ROWS ONLY;
Visit this page to learn more about row limiting clause for top-N queries in Oracle Database 12c Release 1 (12.1)

Related

Infinite scroll data pull

I have an infinite scroll scipt that is pulling data and displaying it just fine. However, I am finding that when you scroll down the data pull starts again at the beginning. Right now I have 8 rows for testing in the database to make it easy. My control to get the next data set does not seem to be working otherwise it would go to the next set of results?
//item per page
$limit = 5;
$page =(int)(!isset($_GET['p']))?1: $_GET['p'];
// sql query
$sqlContent="SELECT make, model, year, carid FROM cars";
//Query start point
$start =($page * $limit)- $limit;
$resContent=$DB_con->query($sqlContent);
$rows_returned= $resContent->rowCount();//->fetchColumn();
// query for page navigation
if( $rows_returned > ($page * $limit)){
$next =++$page;
}
$sqlContent = $sqlContent ." LIMIT $start, $limit";
$finalContent = $DB_con->query($sqlContent);
if($finalContent === false) {
trigger_error('Error: ' . $DB_con->error, E_USER_ERROR);
} else {
$rows_returned= $finalContent->rowCount();//->fetchColumn();
}
?>
then display the results:
<?php while($rowContent = $finalContent->fetch()) {
$year = $rowContent['year'];
$make = $rowContent['make'];
$model = $rowContent['model'];
?>
<div class="row">
<div class="ride"><?php echo "$year $make $model"; ?></div>
</div>
<?php } ?>
</div>
</div>
<!--page navigation-->
<?php if(isset($next)):?>
<div class="nav">
<a href='index.php?p=<?php echo $next?>'>Next</a>
</div>
<?php endif ?>
</div>
This is something that I adapted for PHP from my days as a classic-asp programmer.
It provides a nice counter along with First, Last, Next & Previous links.
First is your sql query with two select statements depending on the number of records you want to show per page AND the total number of records. (in case the number you want to show is actually larger than the number of records in the db).
<?php
require'connections/conn.php';
$maxRows_rsList = 10; // the number of records you want to show per page
$pageNum_rsList = 0;
if (isset($_GET['pageNum_rsList'])) {
$pageNum_rsList = $_GET['pageNum_rsList'];
}
$startRow_rsList = $pageNum_rsList * $maxRows_rsList;
$query_rsList = $conn->prepare("SELECT make, model, year, carid FROM cars");
$query_limit_rsList = $conn->prepare("SELECT make, model, year, carid FROM cars LIMIT $startRow_rsList, $maxRows_rsList");
$query_limit_rsList->execute();
$row_rsList = $query_limit_rsList->fetch(PDO::FETCH_ASSOC);
if (isset($_GET['totalRows_rsList'])) {
$totalRows_rsList = $_GET['totalRows_rsList'];
} else {
$all_rsList = $query_rsList->execute();
$totalRows_rsList = $query_rsList->rowCount();
}
$totalPages_rsList = ceil($totalRows_rsList/$maxRows_rsList)-1;
$queryString_rsList = "";
if (!empty($_SERVER['QUERY_STRING'])) {
$params = explode("&", $_SERVER['QUERY_STRING']);
$newParams = array();
foreach ($params as $param) {
if (stristr($param, "pageNum_rsList") == false &&
stristr($param, "totalRows_rsList") == false) {
array_push($newParams, $param);
}
}
if (count($newParams) != 0) {
$queryString_rsList = "&" . htmlentities(implode("&", $newParams));
}
}
$queryString_rsList = sprintf("&totalRows_rsList=%d%s", $totalRows_rsList, $queryString_rsList);
$currentPage = $_SERVER["PHP_SELF"]; // so we stay on the same page just changing the recordset data
?>
Then our output
<table cellpadding="5" cellspacing="0" border="0">
<?php if($totalRows_rsList > $maxRows_rsList) { ?>
<tr>
<td colspan="2"><?php echo ($startRow_rsList + 1) ?> to <?php echo min($startRow_rsList + $maxRows_rsList, $totalRows_rsList) ?> of <?php echo $totalRows_rsList ?> cars<br />
<table border="0">
<tr>
<?php if ($pageNum_rsList > 0) { // Show if not first page ?>
<td width="25" nowrap="nowrap">
First
</td>
<?php } // Show if not first page ?>
<?php if ($pageNum_rsList > 0) { // Show if not first page ?>
<td width="25" nowrap="nowrap">
Prev
</td>
<?php } // Show if not first page ?>
<?php if ($pageNum_rsList < $totalPages_rsList) { // Show if not last page ?>
<td width="25" nowrap="nowrap">
Next
</td>
<?php } // Show if not last page ?>
<?php if ($pageNum_rsList < $totalPages_rsList) { // Show if not last page ?>
<td width="25" nowrap="nowrap">
Last
</td>
<?php } // Show if not last page ?>
</tr>
</table></td>
</tr>
<?php } else if(($totalRows_rsList == $maxRows_rsList) || ($totalRows_rsList < $maxRows_rsList)) { ?>
<tr><td colspan="2"> </td></tr>
<tr><td colspan="2"><?php echo ($startRow_rsList + 1) ?> to <?php echo min($startRow_rsList + $maxRows_rsList, $totalRows_rsList) ?> of <?php echo $totalRows_rsList ?> cars<br /></td></tr>
<?php } ?>
<tr><td>
<?php do {
$year = $row_rsList['year'];
$make = $row_rsList['make'];
$model = $row_rsList['model'];
?>
<div class="row">
<div class="ride"><?php echo "$year $make $model"; ?></div>
</div>
<?php } while($row_rsList = $query_limit_rsList->fetch(PDO::FETCH_ASSOC)) ?>
</div>
</div>
</td></tr>
</table>
$page =(int)(!isset($_GET['p']))?1: $_GET['p'];
should actually be
$page =(!isset($_GET['p']))?1: (int)$_GET['p'];
what you are doing is casting the boolean result of isset as an integer

How do i generate more than 1 pdfs on click of a button

I am creating a component for teachers where in teacher can generate pdf for all the students who have completed the course.
Checking all the students and pdfs should be generated and saved on disk. After which a download link is provided to download the zip of all the pdfs generated. This is what i want to achieve. I am using fpdf for generating pdf.
Any suggestions ?
Below is the form that is posted and students id-
<form
action="<?php echo JRoute::_('index.php?option=com_mentor&view=download_certificate&cid=' . $cid . '&Itemid=529') ?>"
name="download_certificate" method="post" id="download_certificate">
<table class="adminlist" border="1" cellpadding="0" cellspacing="0"
style="table-layout: fixed" id="content">
<thead>
<tr>
<th class="nowrap" style="width: 35px">
<input type="checkbox" name="selectall" id="selectall">
</th>
<th class="nowrap" align="center">
<?php echo JText::_('COM_MENTOR_USER_NAME'); ?>
</th>
<th class="nowrap" style="width: 140px">
<?php echo JText::_('COM_MENTOR_COURSE_STATUS'); ?>
</th>
<th class="nowrap" style="width: 140px">
<?php echo JText::_('COM_MENTOR_ENROLLMENT_DATE'); ?>
</th>
<th class="nowrap" style="width: 140px">
<?php echo JText::_('COM_MENTOR_ACTIVITY'); ?>
</th>
<th class="nowrap" style="width: 50px">
<?php echo JText::_('COM_MENTOR_SCORE'); ?>
</th>
<th class="nowrap" style="width: 50px">
<?php echo JText::_('COM_MENTOR_RESULT'); ?>
</th>
</tr>
</thead>
<tbody>
<?php
//echo '<pre>';print_r($this->mentor_details); die;
foreach ($this->mentor_details as $students) {
$cid = $this->mentor_details['cid'];
$i = 1;
foreach ($students['students'] as $student) {
$userid = $student['id'];
// echo '<pre>';
// print_r($student);
// die;
?>
<tr class="status" id="<?php echo $userid ?>">
<td align="center">
<input type="checkbox" id="<?php echo $userid ?>" name="check[]" class="checkbox1"
value="<?php echo $userid ?>">
</td>
<td>
<a href="<?php echo JRoute::_('index.php?option=com_mentor&view=grader&cid=' . $cid . '&uid='
. $userid . $itemid) ?>">
<?php echo $student['username']; ?>
</a>
</td>
<!-- <td>
<?php// echo $student['email']; ?>
</td> -->
<td align="center">
<?php
$incomplete = $completed = $not_started = 0;
for ($k = 0; $k < count($student['elements']); $k++) {
foreach ($student['elements'] as $elements) {
if ($elements['userid'] == $userid) {
// echo '<pre>';print_r($elements); die;
if ($elements['element']['cmi.core.lesson_status'] == 'incomplete') {
$incomplete++;
} else {
$completed++;
}
}
}
}
if ($incomplete == 0 && $completed == 0) {
echo 'Not yet started';
} else {
if ($completed == count($student['elements'])) {
echo 'Completed';
} else {
echo 'Incomplete';
}
}
?>
</td>
<td align="center">
<?php
if (!empty($student['timestart'])) {
$date = date('d-m-Y H:i', $student['timestart']);
echo $date;
} else {
echo "Not yet started";
} ?>
</td>
<td align="center">
<?php
if (!empty($student['activity']['lasttime']) && (!empty($student['activity']['starttime']))) {
$start_date = date('d-m-Y H:i', $student['activity']['starttime']);
$last_date = date('d-m-Y H:i', $student['activity']['lasttime']);
echo $start_date . '<br/>' . $last_date;
} else {
echo "-";
} ?>
</td>
<td align="center">
<?php
$grades = $student['grades'];
$total_grade = array();
$j = 0;
//for ($j = 0; $j < count($grades); $j++) {
// $total_grade[$j] = $grades[$j]['finalgrade'];
//}
//print_r($total_grade);die;
if (!empty($grades)) {
//echo number_format(array_sum($total_grade), 2);
$total_grade[$j] = $grades[$j]['finalgrade'];
echo number_format($total_grade[$j], 2);
} else {
echo '-';
}
//echo '<pre>';
//print_r($student['grades']);
//die;
?>
</td>
<td align="center">
<?php
//echo '<pre>';print_r($student);die;
if (!empty($student['scores'])) {
if (isset($grades[$j]['feedbacktext'])) {
echo $grades[$j]['feedbacktext'];
} else {
echo '-';
}
} else {
echo '-';
}
?>
</td>
</tr>
<?php $i++;
}
} ?>
</tbody>
</table>
</form>
<script>
function checked_value() {
var checkedValue = [];
var $len = $(".checkbox1:checked").length;
if ($len == 0) {
alert('Please select user');
}
// else if ($len > 1) {
// alert('Please select a single user only.');
// }
else {
$(".checkbox1").each(function () {
var $this = $(this);
if ($this.is(":checked")) {
checkedValue.push($this.attr("id"));
}
});
$("#download_certificate").submit();
</script>
On Clicking image tag, form is submitted with the students id and I am getting students data, his name, grades, course,
<img src="/components/com_mentor/images/certificate_blue.png" class="certificate-ico right"
title="Download Certificate" onclick="checked_value();"/>
After this processing, page is redirected to pdf.php page
require_once('/wamp/opt/bitnami/apache2/htdocs/lms/lib/fpdf/fpdf.php');
$pdf = new FPDF(); $pdf->SetFont('times', '', 12);
$pdf->SetTextColor(50, 60, 100); $pdf->AddPage('L');
$pdf->SetDisplayMode(real, 'default'); $pdf->SetXY(10, 60);
$pdf->SetFontSize(12);
$pdf->Write(5, 'Dear Ms.XYX');
$filename = "test.pdf";
$dir = "/assets/";
$pdf->Output($dir . $filename, 'F');
Thanks guys for your help.. Solved my question.
Looped through the pdf function for n no. of users.

Pagination always missing 1 row

I have a pagination code that fetch data from DB and show them in Table paginated, but always missing the last row added in the database, I have no idea why..
this my code ;
if(isset($_GET['page'])){
$page=$_GET['page'];
}else $page=1;
$obj=new action_a_DB();
$totall= $obj->getNmbLgForPages() ; // number of all articles.
$pagination=new pagination($totall,10 /*number of content per page*/,$page,5 /*number of button to show*/);
$start = $pagination->Start ;
$end = $pagination->End ;
// get the info from the db
$total_page = ceil($totall/10);
$result = $obj->getAllArticle($start,$end) ;
}
pagination.php
...
public function Show_Pagination($link,$get='page',$div_class_name='pagination')
{
if($this->Pages==1)return;
echo'<div class="'.$div_class_name.'">';
if($this->Page_number>1)echo 'Pre ';
else echo '<a >Pre</a> ';
//print button
$this->Buttons=(int)$this->Buttons;
$start_counter = $this->Page_number-floor($this->Buttons/2);
$end_conter = $this->Page_number+floor($this->Buttons/2);
if($start_counter<1) $end_conter=$end_conter+abs($start_counter);
if($end_conter>$this->Pages) $start_counter=$start_counter-($end_conter-$this->Pages);
if(($this->Page_number-floor($this->Buttons/2))<1)$end_conter ++;
for ($i=$start_counter;$i<=$end_conter;$i++)
{
if($i>$this->Pages || $i<1)continue; //no print less than 1 value or grater than totall page
if($i==$this->Page_number)echo ' <a class="cur">'.$i.'</a> ';
else echo ' '.$i.' ';
}
if($this->Page_number<$this->Pages)echo 'Suiv ';
else echo '<a >Suiv</a> ';
echo'</div>';
}
...
my funtions in action_a_DB.php
function getAllArticle($Start, $End){
$sql = "SELECT * FROM articles order by id desc limit $Start , $End";
$req = mysql_query($sql) or die('Req Invalide: ' . mysql_error());
//return mysql_fetch_array($req);
return $req;
}
function getNmbLgForPages(){
$query=mysql_query("SELECT count(id) from articles") or die('Erreur :'.mysql_error()); //
$totall=mysql_result($query,0);
return $totall;
}
My table
</tr>
<?php if(mysql_fetch_row($result)!=0){
while($data = mysql_fetch_array($result)) {?>
<tbody>
<tr>
<td class="first style1"><?php echo $data['titre']; ?> </td>
<td><?php echo $data['descrition']; ?></td>
<td><img src="img/edit-icon.gif" width="16" height="16" alt="" /></td>
<td><img src="img/hr.gif" width="16" height="16" alt="" /></td>
<td><img src="img/save-icon.gif" width="16" height="16" alt="save" /></td>
</tr></tbody> <?php }
?>
<tfoot><tr id="nav"><td colspan="5"><div> <?php
$pagination->Show_Pagination("index.php?param1=value1",'page','pagination');
?></div></td>
</tr>
<tr id="total"><td colspan="5"><?php echo 'Page : '.$page.' sur '.$total_page.' Nombre totales d\'articles: '.$totall.'' ; ?></td>
</tr>
<?php } else{ ?>
<tr><td align="center" colspan="5">Rien a afficher</td>
</tr></tfoot>
<?php } ?>
</table>
How can i Fix this problem ?
Thanks a lot,
My mistake was here
<?php if(mysql_fetch_row($result)!=0){
I have to use mysql_num_rows not mysql_fetch_row
So I use
<?php if(mysql_num_rows($result)!=0){
Why, When my query is executed, it returns a result set with a pointer to the first record. Then each fetch returns a line and moves the pointer to the next line or returns false if there is no next row in the result set, then the while to process all the results. In my case, the first line of my resource is used in if so it fails in the display.
Now work fine, thanks to Bovino for explain and to you all

Using foreach to display results

I'm trying to write some sort of forum homepage, based off work someone else did. Here's what I've got so far:
Forums
<?php
$crumbs = explode(",", $user['data']['depts']);
foreach ($crumbs as &$value) {
$data = $db->query("SELECT * FROM tbl_depts WHERE id = '" . $value . "'");
$crumb = $data->fetch_assoc();
$data = $db->query("SELECT * FROM tbl_forums WHERE deptid = '" . $value . "'");
$forumcount = $data->num_rows;
$forum = $data->fetch_assoc();
?>
<div class="h3top"><?php echo $crumb['name']; ?></div>
<div class="info2alt">
<?php
while (($row = $data->fetch_array()) !== FALSE) {
$forum[] = $row;
}
foreach ($forum as $row) {
if ($forumcount >= 1) {
if ($forum['lastpost'] == "") {
$forum['lastpost'] = "--";
}
?>
<div class="info4">
<table width="100%" border="0" cellspacing="1" cellpadding="4">
<tr>
<td width="55%" align="left" valign="middle" class="zebraodd"><?php echo $row['name']; ?></td>
<td width="10%">Threads: <?php echo $forum['threadcount']; ?><br />Posts: <?php echo $forum['postcount']; ?></td>
<td width="35%">Last Post: <?php echo $forum['lastpost']; ?></td>
</tr>
</table>
</div>
<?php
}
?>
<?php if ($forumcount >= 1) { ?>
<div class="info3bottom"></div>
<?php
}
}
?>
</div>
<?php
}
?>
This is the current data in the table:
Now, when I try to use this code, I get this:, such that the first one is shown so many times, however, the next one does not appear.
How do I fix this?
you want to use $value['threadcount'] etc. $forum is the array containing all the rows. i wonder that you get some output at all …
fetch_assoc() will only fetch a single row from the resultset. you'd have to use a loop to fill an array:
while(($row = $data->fetch_assoc()) !== FALSE) {
$forum[] = $row;
}
you can then iterate over your $forum array with a foreach loop:
foreach($forum as $row) {
echo htmlspecialchars($row['threadcount']);
// etc.
}
trying to fix this mess …
<?php
$crumbs = explode(",", $user['data']['depts']);
foreach ($crumbs as $crumb) { ?>
<div class="h3top"><?php echo htmlspecialchars($crumb['name']);?></div>
<?
}
$result = $db->query("SELECT * FROM tbl_forums WHERE deptid = " . (int)$id . "");
$forumcount = $result->num_rows;
while(($row = $data->fetch_assoc()) !== FALSE) {
if ($row['lastpost'] == "") { $row['lastpost'] = "--";}
?>
<div class="info2alt">
<div class="info4">
<table width="100%" border="0" cellspacing="1" cellpadding="4">
<tr>
<td width="55%" align="left" valign="middle" class="zebraodd"><?php echo htmlspecialchars($forum['name']); ?></td>
<td width="10%">Threads: <?php echo htmlspecialchars($forum['threadcount']); ?><br />Posts: <?php echo htmlspecialchars($forum['postcount']); ?></td>
<td width="35%">Last Post: <?php echo htmlspecialchars($forum['lastpost']); ?></td>
</tr>
</table>
</div>
<div class="info3bottom"></div>
<?php
}
?>

SQL database interaction

I am making a database, which will interact with a SQL table.
What I have achieved so far:
Add rows to the table.
Delete rows from the table.
Search rows from the table.
Paginate the results.
What I need to achieve:
A log in prompt when a guest tries to
access the page.
In fact, I have successfully installed a log in script for it, but it seems to not work properly, here is the error:
Fatal error: Allowed memory size of
25165824 bytes exhausted (tried to
allocate 77824 bytes) in
/home/vol3/byethost12.com/b12_3598660/htdocs/coordbase/database.php on line 238
Now that I do not have permission to allow more memory from my host, I would need a way around this.
I have already tried separating the file into multiple pages, but it seems that it still tried to allocate the same amount of bytes.
Here is the file:
<?php
require_once('db.php'); // for database details
ini_set('display_errors',1);
error_reporting (E_ALL ^ E_NOTICE);
require('../include/session.php');
if (!$session->isMember())
{
header("../resources.php");
}
else
{
$self = $_SERVER['PHP_SELF']; //the $self variable equals this file
$ipaddress = ("$_SERVER[REMOTE_ADDR]"); //the $ipaddress var equals users IP
$connect = mysql_connect($host,$username,$password) or die('<p class="error">Unable to connect to the database server at this time.</p>');
mysql_select_db($database,$connect) or die('<p class="error">Unable to connect to the database at this time.</p>');
require('../include/header.php');//Page Header
if($_GET['cmd'] == "delete")
{
echo "<center><h1>Delete</h1></center>";
if(isset($_POST['delete'])) {
$time = date("Y-m-d H:i:s");
$queryc = "DELETE FROM coords WHERE id=".$_GET['id'].";";
$resultc = mysql_unbuffered_query("$queryc") or die("Could not delete the selected base from the database at this time, please try again later.");
$sqls = "INSERT INTO reports SET ip='$ipaddress', date='$time';";
//run the query. if it fails, display error
$report = mysql_unbuffered_query("$sqls") or die("Could not add report to the database, but the base has been deleted successfully.");
echo "<center>The selected base has been deleted from the database successfully!<br>
<a href=http://www.teamdelta.byethost12.com/coordbase/database.php>Back to Main</a><br><br>
<font color=\"red\"><b>YOUR IP HAS BEEN LOGGED. ABUSE OF THIS SYSTEM WILL RESULT IN AN IP BAN!</b></font></center>";
}
else
{
$queryd = "SELECT * FROM coords WHERE id=".$_GET['id'].";";
$resultf = mysql_unbuffered_query("$queryd") or die('<p class="error">There was an unexpected error grabbing the base from the database.</p>');
?>
<center>
<table>
<table width="83%" border="1">
<tr>
<td ><b>Tag</b></td>
<td ><b>Guild</b></td>
<td ><b>Player</b></td>
<td ><b>Base</b></td>
<td ><b>Location</b></td>
<td ><b>Econ</b></td>
<td ><b>Comments</b></td>
</tr>
<?php
while ($rowa = mysql_fetch_array($resultf)) {
$id = stripslashes($rowa['id']);
$tag = stripslashes($rowa['tag']);
$guild = stripslashes($rowa['guild']);
$name = stripslashes($rowa['name']);
$base = stripslashes($rowa['base']);
$location = stripslashes($rowa['location']);
$comment = stripslashes($rowa['comment']);
$id = stripslashes($rowa['id']);
$econ = stripslashes($rowa['econ']);
$maxecon = stripslashes($rowa['maxecon']);
echo('<tr><center><td>['.$tag.']</td><td>'.$guild.'</td><td>'.$name.'</td><td>'.$base.'</td><td>'.$location.'</td><td>'.$econ.'/'.$maxecon.'</td><td>'.$comment.'</td></center></tr>');
}
?>
</table>
</table>
<b>Are you sure you wish to delete the selected base?</b>
<br>
<input type="button" value="Cancel" id="button1" name="button1"onclick="window.location.href='database.php';">
<form action="<?php $self ?>" name="deletefrm" method="post" align="right" valign="bottom" onsubmit="return validate();">
Confirm Delete<input type=checkbox name="confirm"><input type="submit" name="delete" value="Delete" />
</form>
</center>
<br>
<center><font color="red"><b>YOUR IP WILL BE LOGGED. ABUSE OF THIS SYSTEM WILL RESULT IN AN IP BAN!</b></font></center>
<?php
}
}
else
{
if(isset($_POST['add'])) {
?>
<tr>
<td style="background: url(http://www.teamdelta.byethost12.com/barbg.jpg) repeat-x top;">
<center><b><font color="#F3EC84">»Info«</font></b></center>
</td>
</tr>
<tr><!--info content-->
<td style="background: #222222;">
<?php
//fetch data
$data = strip_tags(mysql_real_escape_string($_POST['list']));
$comment = strip_tags(mysql_real_escape_string($_POST['comment']));
$data_lines = explode( "\\r\\n", $data );
$comment_lines = explode("\\r\\n", $comment);
for($i=0;$i<count($data_lines);$i++)
{
$data_fields = explode( ",", $data_lines[$i]);
$time = time();
$queryb = "INSERT INTO coords SET
tag='{$data_fields[0]}',
guild='{$data_fields[1]}',
name='{$data_fields[2]}',
base='{$data_fields[3]}',
econ='{$data_fields[5]}',
maxecon='{$data_fields[6]}',
location='{$data_fields[4]}',
comment='{$comment_lines[$i]}',
ipaddress='$ipaddress' ,
date='$time';";
// if it succeeds, display message
if (mysql_unbuffered_query($queryb))
{
echo('<p class="success">Successful posting of ['.$data_fields[3].']!</p>');
}
else
{
echo('<p class="error">Error could not post ['.$data_fields[3].'] to database!</p>');
}
}//end for loop
}//end if $_POST['add'] statement
?>
<?php
if (isset($_GET['cmd']) == "add"){
?>
<!--start inputbox-->
<center><table width="100%">
<tr>
<td style="background: url(http://www.teamdelta.byethost12.com/barbg.jpg) repeat-x top;">
<center><b><font color="#F3EC84">»Add«</font></b></center>
</td>
</tr>
<tr>
<td style="background: #222222;"><!-- at the bottom of the page, we display our comment form -->
<form action="<?php $self ?>" method="post" onsubmit="return valid(this)">
<table width="100%" border ="0" valign="top">
<tr>
<td>
List:
</td>
<td align="left">
<textarea name="list" rows="10" cols="70"></textarea>
</td>
<td valign="top">
<font color="red"><b>[Post list arranged like so!]</b></font><br>
<br>
E.G:<br>
<br>
(tag),(guild),(player,(base),(coordinates),(econ),(maxecon)<br>
~TD~,~Team Delta~,DarkLink,Base1,D03:56:21:11,101,101<br>
FARM,Guild896,player 5,Base #3,D69:62:89:10,98,135<br>
</td>
</tr>
</tr>
<td>
Comment:
</td>
<td>
<textarea name="comment" rows="10" cols="70"></textarea>
</td>
<td>
<font color="red"><b>[Post comments on a new line for each base!]</b></font><br>
E.G "PS 10/10 PR 10/10"<br>
"PR 5/5 DT 10/10"
</td>
<td>
<td>
</td>
<td valign="bottom" align="right">
<p>
<input type="submit" name="add" value="Add" />
</p>
</td>
</tr>
</table>
</form>
Back to Main
</td>
</tr>
</table></center>
<!--end input box-->
<?php
}
else
{
if (isset($_GET['search']) == "do"){
$title = "<center><h1>Results</h1>";
$search = stripslashes($_GET['searchterm']);
$asearch = trim($search);
$bsearch = strip_tags($asearch);
$csearch = mysql_real_escape_string($bsearch);
$types = "types of search";
switch ($_GET['type']){
case 'name':
$types = "name";
break;
case 'tag':
$types = "tag";
break;
case 'guild':
$types = "guild";
break;
default:
$types = "";
echo "<center><b>Please select a search type before continuing! You are being redirected, please wait.<br>
Click here, if you do not wish to wait.</b></center>";
header("Refresh: 5; url=http://www.teamdelta.byethost12.com/coordbase/database.php");
exit;
break;
}
$querya = "SELECT * FROM coords WHERE `{$types}` LIKE '%{$csearch}%' ORDER BY `{$types}`;";
$result = mysql_unbuffered_query("$querya") or die("There was an error.<br/>" . mysql_error() . "<br />SQL Was: {$querya}");
if (mysql_num_rows($result) < 1) {
echo $title;
echo "<b><center>We are sorry to announce that the search term provided: \"{$search}\", yielded no results. <br>"
."<hr>"
."New Search</center></b>";
exit;
}else {
echo $title;
?>
<b>for "<?php echo $search;?>".</b>
<hr>
<table>
<table width="83%" border="1">
<tr>
<td ><b>Tag</b></td>
<td ><b>Guild</b></td>
<td ><b>Player</b></td>
<td ><b>Base</b></td>
<td ><b>Location</b></td>
<td ><b>Econ</b></td>
<td ><b>Comments</b></td>
<td ><b>Delete</b></td>
</tr>
<?php
while ($row = mysql_fetch_array($result)) {
$id = stripslashes($row['id']);
$tag = stripslashes($row['tag']);
$guild = stripslashes($row['guild']);
$name = stripslashes($row['name']);
$base = stripslashes($row['base']);
$location = stripslashes($row['location']);
$comment = stripslashes($row['comment']);
$id = stripslashes($row['id']);
$econ = stripslashes($row['econ']);
$maxecon = stripslashes($row['maxecon']);
echo('<tr><center><td>['.$tag.']</td><td>'.$guild.'</td><td>'.$name.'</td><td>'.$base.'</td><td>'.$location.'</td><td>'.$econ.'/'.$maxecon.'</td><td>'.$comment.'</td><td><a href=database.php?id='.$id.'&cmd=delete>Delete</a></td></center></tr>');
}
echo "New Search";
?>
</table>
</table>
<?php
}
}
else{
// find out how many rows are in the table
$sql = "SELECT COUNT(*) FROM coords";
$result = mysql_unbuffered_query($sql, $connect) or trigger_error("SQL", E_USER_ERROR);
$r = mysql_fetch_row($result);
$numrows = $r[0];
// number of rows to show per page
$rowsperpage = 10;
// find out total pages
$totalpages = ceil($numrows / $rowsperpage);
// 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;
} // end if
// if current page is greater than total pages...
if ($currentpage > $totalpages) {
// set current page to last page
$currentpage = $totalpages;
} // end if
// if current page is less than first page...
if ($currentpage < 1) {
// set current page to first page
$currentpage = 1;
} // end if
// the offset of the list, based on current page
$offset = ($currentpage - 1) * $rowsperpage;
?>
</center>
<!--start inputbox-->
<center>
<table width="83%">
<tr>
<td style="background: url(http://www.teamdelta.byethost12.com/barbg.jpg) repeat-x top;">
<center><b><font color="#F3EC84">»Search«</font></b></center>
</td>
</tr>
<tr>
<td style="background: #222222;"><!-- at the bottom of the page, we display our comment form -->
<form method="GET" action="<?php echo $_SERVER['PHP_SELF'];?>" name="searchForm" onsubmit="return valid(this)">
<table border ="0" width="100%">
<tr>
<td><center>
Search For: <input type="text" name="searchterm">
Player <input type="radio" name="type" value="name" checked> |
Guild Tag <input type="radio" name="type" value="tag"> |
Guild Name <input type="radio" name="type" value="guild">
<input type="hidden" name="search" value="do">
<input type="submit" value="Search">
Add new bases
</tr>
</center>
</td>
</tr>
</form>
</td>
</tr>
</table>
</center>
<!--end input box-->
<hr>
<center>
<table>
<table width="83%" border="1">
<tr>
<td ><b>Tag</b></td>
<td ><b>Guild</b></td>
<td ><b>Player</b></td>
<td ><b>Base</b></td>
<td ><b>Location</b></td>
<td ><b>Econ</b></td>
<td ><b>Comments</b></td>
<td ><b>Delete</b></td>
</tr>
<?php
$query = "SELECT * FROM coords ORDER BY `tag` ASC LIMIT $offset, $rowsperpage;";
$result = mysql_unbuffered_query("$query") or die('<p class="error">There was an unexpected error grabbing routes from the database.</p>');
// while we still have rows from the db, display them
while ($row = mysql_fetch_array($result)) {
$id = stripslashes($row['id']);
$tag = stripslashes($row['tag']);
$guild = stripslashes($row['guild']);
$name = stripslashes($row['name']);
$base = stripslashes($row['base']);
$location = stripslashes($row['location']);
$comment = stripslashes($row['comment']);
$id = stripslashes($row['id']);
$econ = stripslashes($row['econ']);
$maxecon = stripslashes($row['maxecon']);
echo('<tr><center><td>['.$tag.']</td><td>'.$guild.'</td><td>'.$name.'</td><td>'.$base.'</td><td>'.$location.'</td><td>'.$econ.'/'.$maxecon.'</td><td>'.$comment.'</td><td><a href=database.php?id='.$id.'&cmd=delete>Delete</a></td></center></tr>');
}
?>
</table>
</table>
<?php
/****** 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
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=1'><<</a> ";
// get previous page num
$prevpage = $currentpage - 1;
// show < link to go back to 1 page
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$prevpage'><</a> ";
} // end if
// 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
echo " [<b>$x</b>] ";
// if not current page...
} else {
// make it a link
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$x'>$x</a> ";
} // end else
} // end if
} // end for
// if not on last page, show forward and last page links
if ($currentpage != $totalpages) {
// get next page
$nextpage = $currentpage + 1;
// echo forward link for next page
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$nextpage'>></a> ";
// echo forward link for lastpage
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$totalpages'>>></a> ";
} // end if
/****** end build pagination links ******/
}//end else of search
}//end else of add
}//end else of delete
?>
</center>
<?php
require('../include/footer.php');//Page footer
}
?>
This would be around line 238:
<?php
//fetch data
$data = strip_tags(mysql_real_escape_string($_POST['list']));
$comment = strip_tags(mysql_real_escape_string($_POST['comment']));
$data_lines = explode( "\\r\\n", $data );
$comment_lines = explode("\\r\\n", $comment);
for($i=0;$i<count($data_lines);$i++)
{
$data_fields = explode( ",", $data_lines[$i]);
$time = time();
$queryb = "INSERT INTO coords SET
tag='{$data_fields[0]}',
guild='{$data_fields[1]}',
name='{$data_fields[2]}',
base='{$data_fields[3]}',
econ='{$data_fields[5]}',
maxecon='{$data_fields[6]}',
location='{$data_fields[4]}',
comment='{$comment_lines[$i]}',
ipaddress='$ipaddress' ,
date='$time';";
// if it succeeds, display message
if (mysql_unbuffered_query($queryb))
{
echo('<p class="success">Successful posting of ['.$data_fields[3].']!</p>');
}
else
{
echo('<p class="error">Error could not post ['.$data_fields[3].'] to database!</p>');
}
}//end for loop
}//end if $_POST['add'] statement
?>
I have noticed that the memory exceeds the limit when I include session.php to my file.
The problem is that I need that file for my log in prompt to work.
Check for recursions, this code cannot possibly exhaust memory. Try adding echo's around the code.

Categories