How can I optimise and improve the speed of this MySQL query? - php

I am trying to get information from my database and display it. Here is a screenshot of what the page looks like:
The page loads really slow
Is there any way to make it load and display the data faster?
Here is the code.
<table align="center" class="pTable">
<tr class="main"> <th class="pTableHeader"> ID </th> <th class="pTableHeader"> Room </th> <th class="pTableHeader"> Status</th> </tr>
<?php
gc_enable();
gc_collect_cycles();
flush();
$this->mysql = new sqli('HIDDEN','HIDDEN','HIDDEN','HIDDEN');
$bots = $this->mysql->fetch_array("SELECT `pid`,`room`,`id` from `bots`;");
foreach ($bots as $b) {
if(is_numeric($b["room"])) {
$xat = file_get_contents('http://www.xat.com/xat'.trim($b["room"]));
$name = sp($xat, '<h1> ', '</h1>');
}
else $name = $b['room'];
//$b["pid"] = isset($b["pid"])?$b["pid"]:false;
//$online = \"start.php {$b['id']} {$b['id']}\"", $output) && count($output) > 1 ? true : false;
$online = file_exists("/proc/{$b['pid']}" )?true:false;
if($online === true) $status = "<font color='green'>Online</font> <div style='float:right'><img src='http://fexbots.com/Images/Pawns/online.png'> <a href='/botinfo?botid={$b["id"]}'>More info</a></div>";
else $status = "<font color='red'>Offline</font> <div style='float:right'><img src='http://fexbots.com/Images/Pawns/offline.png'> <a href='/botinfo?botid={$b["id"]}'>More info</a></div>";
if($b["room"] === '') {
$name = "No Room";
$status = "<font color='red'>Not Setup!</font> <div style='float:right'><img src='http://fexbots.com/Images/Pawns/hang.png'> <a href='/botinfo?botid={$b["id"]}'>More info</a></div>";
echo '<tr> <td> '.$b["id"].' </td> <td> No Room <td> '.$status.'</td> </tr>';
}
else echo "<tr> <td> ".$b['id']." </td> <td> <a href='http://www.xat.com/$name'>$name</a> <td> ".$status."</td> </tr>";
}
function sp($content, $start, $end, $lower=false) {
if($lower!=false) {
$content = strtolower($content);
$start = strtolower($start);
$end = strtolower($end);
}
$content = substr($content, strpos($content,$start)+strlen($start));
$content = substr($content, 0, strpos($content,$end));
return $content;
}
?>
</table>

You seem to download the content from an URL inside the loop. Maybe that is the cause to why it is slow and not the mysql query itself.
Try to write out some timestamps or comment some code out to see what is causing it to be slow.

Related

Fatal error: Call to a member function result_array() on a non-object in

Before, I would say sorry because ask this question again. I have searched the related topic here about 'Fatal error : call to a member function' and try it the solution but this error still there. So, today I would ask your help to solve this error.
This error appears when I press the search key and the result is
Fatal error: Call to a member function result_array() on a non-object in
not the real data.
This is my program :
Controller:
public function gridSearchAll() {
$this->load->helper('form');
$this->load->helper('lightutility');
$this->load->model('moMasterMng');
$this->load->model('moMasterConf');
$this->load->model('moMasterFilling');
$this->load->model('moUser');
$objMUser = new moUser();
$objMMasterMng = new moMasterMng();
$objMMasterFill = new moMasterFilling();
$objMMasterConf = new moMasterConf();
$ucValue = array();
$data = array();
$result = '';
$alertMsg = '';
// get data
$data['StartPage'] = $this->input->post('hidStartPage');
$data['DisplayRows'] = longRows();
$data['Ordering'] = $this->input->post('ddlOrdering');
$data['OrderingType'] = $this->input->post('ddlOrderingType'); $data['DateRetentionFrom'] = reverseDate(cleanText($this->input->post('txtDateRetentionFrom')));
$data['DateRetentionTo'] = reverseDate(cleanText($this->input->post('txtDateRetentionTo')));
$data['DateArchivedFrom'] = reverseDate(cleanText($this->input->post('txtDateArchivedFrom')));
$data['DateArchivedTo'] = reverseDate(cleanText($this->input->post('txtDateArchivedTo')));
$data['Category'] = $this->input->post('ddlCategory');
$data['Keyword'] = $this->input->post('txtKeyword');
//validation
if(!isValidDateSystem($data['DateArchivedFrom']) AND !isValidDateSystem($data['DateArchivedTo'])){
$alertMsg .= 'Penulisan Tanggal Arsip Tidak Valid!\n';
}
if(!isValidDateSystem($data['DateRetentionFrom']) AND !isValidDateSystem($data['DateRetentionTo'])){
$alertMsg .= 'Penulisan Tanggal Retensi Tidak Valid!\n';
}
if(empty($data['DateArchivedFrom']) XOR empty($data['DateArchivedTo'])){
$alertMsg .= 'Tanggal Arsip Tidak Boleh Kosong Salah Satu!\n';
}
if(empty($data['DateRetentionFrom']) XOR empty($data['DateRetentionTo'])){
$alertMsg .= 'Tanggal Retensi Tidak Boleh Kosong Salah Satu!\n';
}
$i = 0;
$no = $data['StartPage'] + 1;
$result .= '<table class="listcoll-tb" cellpadding="0" cellspacing="0">
<tr class="head">
<td class="cell">No.</td>
<td class="cell2">Tgl Arsip</td>
<td class="cell2">Ditinjau Kembali</td>
<td class="cell2">Judul/Nama</td>
<td class="cell2">No Batch</td>
<td class="cell2">Deskripsi</td>
<td class="cell2">Pemilik/Instansi</td>
<td class="cell2">Lokasi</td>
<td class="cell2">Petugas Input</td>
<td class="cell2">Petugas Verifikasi</td>
</tr>';
if($alertMsg != ''){
alert($alertMsg);
}
else{
$dt = $objMMasterFill->populateMasterDescriptionsFilling($data);
foreach($dt as $value)
{
$rowOdd = 'odd2';
if($i % 2 == 0){
$rowOdd = 'odd1';
}
$id = $value['ID'];
$instance = '';
$instance = $objMMasterConf->getAncestorB($value['InstanceID'], 'instance');
$attCount = $objMMasterMng->getMasterFillFileCount($id);
if($attCount == 0){
$attCount = '-';
}
else{
$attCount .= ' file';
}
if($value['DateArchived'] != '0000-00-00'){
$value['DateArchived'] = reverseDate($value['DateArchived']);
}
else{
$value['DateArchived'] = '';
}
$userEntry = $objMUser->getUserName($value['UserIDEntry']);
$userVerif = $objMUser->getUserName($value['UserIDVerification']);
$result .= '
<tr class="row '.$rowOdd.'" id="'.$id.'">
<td class="cell">
<div class="btn-panel2">
'.$no.'.
<div class="inner hide">
Detail
</div>
</div>
</td>
<td class="cell2">
'.$value['DateArchived'].'
</td>
<td class="cell2">
'.$value['DateRetention'].'
</td>
<td class="cell2">
'.$value['Title'].'
</td>
<td class="cell2">
'.$value['Code'].'
</td>
<td class="cell2">
'.$value['Description'].'
</td>
<td class="cell2">
'.$instance.'
</td>
<td class="cell2">
'.$value['ClassLoc'].'
</td>
<td class="cell2">
'.$userEntry.'
</td>
<td class="cell2">
'.$userVerif.'
</td>
</tr>
';
$i ++;
$no ++;
}
}
if($i < 3 AND $i > 0){
$result .= '
<tr class="row">
<td class="cell2" style="height:120px;"></td>
<td class="cell2" colspan="12"></td>
</tr>';
}
elseif($i == 0){
$result .= '
<tr class="row">
<td class="cell2" colspan="12" style="height:160px;">
<div class="empty">Kosong</div>
</td>
</tr>';
}
$result .= '</table>';
$result .= $this->load->view('userControls/lib/ucTooltip', '', true);
return $result;
}
Model:
public function populateMasterDescriptionsFilling($data){
$result;
$where = array();
$order = array();
$limit = array();
if(!empty($data['DateArchivedFrom']) AND !empty($data['DateArchivedTo'])){
$where['master_filling.DateArchived >='] = $data['DateArchivedFrom'];
$where['master_fillling.DateArchived <='] = $data['DateArchivedTo'].' 24:00:00';
}
if(!empty($data['DateRetentionFrom']) AND !empty($data['DateRetentionTo'])){
$where['master_filling.DateRetention >='] = $data['DateRetentionFrom'];
$where['master_filling.DateRetention <='] = $data['DateRetentionTo'].' 24:00:00';
}
if(!empty($data['Keyword'])){
$like['master_filling.'.$data['Category']] = $data['Keyword'];
} else{
$like['master_location.Code'] = $data['Keyword'];
}
$order[$data['Ordering']] = $data['OrderingType'];
$limit[$data['DisplayRows']] = $data['StartPage'];
$result = StoredProcedure::MSPSelectMasterDescriptionsDynamicFill($where, $order, $limit);
return $result;
}
Library:
public static function MSPSelectMasterDescriptionsDynamicFill($where, $order, $limit){
self::$loadDb->db->where($where);
self::$loadDb->db->order_by(key($order), $order[key($order)]);
self::$loadDb->db->limit(key($limit), $limit[key($limit)]);
$dset = self::$loadDb->db->get('master_filling');
return $dset->result_array();
}
I would be very grateful for your help.
The error message is telling you that $dset here
$dset = self::$loadDb->db->get('master_filling');
is not the object you think it is. Try adding
error_log('$dset = '.print_r($dset,TRUE));
immediately after that statement, then examine the error log.

Random selection of dynamic check boxes

I am working on building a small php file. I need to select random check boxes. check boxes dynamic as they are pulled from a table with some conditions.
Please let me know if i can randomly select few check boxes say if i get 100 results from the mysql table, 10 random check box needs to be selected.
<?php
$n1=0;
$rambo = strip_tags(#$_POST["assoocc"]);
$r11 = strip_tags(#$_POST["ccdate"]);
$r12 = strip_tags(#$_POST["rrdate"]);
$submit = #$_POST["submit22"];
?>
<body><div>
<form action="selectedcc.php" method="post">
<center> <table width="600" border="1" cellpadding="1" cellspacing="1">
<tr>
<th colspan="3"> Total cases for QA</th>
<th colspan="2"><?php
$ticket=mysql_query("SELECT * FROM us_tickets where (status='Resolved') and (associate='$rambo') and (resolve_date >='$r11') and (resolve_date <='$r12')");
$m1=mysql_num_rows($ticket);
echo "$m1";
?></th>
<th colspan="2"><select name="assoocc1" class="form-control" id="sel1" style="width: 150px;" >
<?php echo "<option value=$rambo selected>".$rambo."</option>";
?>
</select></th>
<th colspan="1"><input type="submit" name="sub" value="Submit For QA "/></th>
</tr>
<tr>
<th>Select Here</th>
<th>Case Id</th>
<th>Task</th>
<th>Number of ASINs</th>
<th>SLA Details</th>
<th>Create date</th>
<th>Resolved date</th>
<th>Rootcause</th></tr>
<?php
if ($submit)
{
if ($rambo&&$r11&&$r12)
{
if ($r11<$r12)
{
$ticket=mysql_query("SELECT * FROM us_tickets where (status='Resolved') and (associate='$rambo') and (resolve_date >='$r11') and (resolve_date <='$r12')");
$m1=mysql_num_rows($ticket);
for($k=0; $k<$m1; $k++)
{
$caseid1 = $task1 = $asin1 = $sla1 = $associate1 = $quer = "";
${"caseid".$k}=mysql_result($ticket,$k, "case_id");
${"task".$k}=mysql_result($ticket,$k, "sub_issue");
${"asin".$k}=mysql_result($ticket,$k, "asin");
${"vendor_credit".$k}=mysql_result($ticket,$k, "vendor_credit");
${"create_date".$k}=mysql_result($ticket,$k, "create_date");
${"resolve_date".$k}=mysql_result($ticket,$k, "resolve_date");
${"root_cause".$k}=mysql_result($ticket,$k, "root_cause");
${"associate".$k}=mysql_result($ticket,$k, "associate");
echo "<tr>"."<th>"."<input type='checkbox' value='${'caseid'.$k}' name='checkboxvar[]'>"."</th>"."<th>".${'caseid'.$k}."</th>"."<th>".${'task'.$k}."</th>"."<th>".${'asin'.$k}."</th>"."<th>".${'vendor_credit'.$k}."</th>"."<th>".${'create_date'.$k}."</th>"."<th>".${'resolve_date'.$k}."</th>"."<th>".${'root_cause'.$k}."</th>"."</tr>";
}
}
else
{
echo "<script>alert('Error:START DATE should be less than END DATE. Go back to QA Home page and enter all fields')</script>";
}
}
else
{
echo "<script>alert('Error:Go back to QA Home page and enter all fields')</script>";
}
}
?>
</table></center></form></div></body></html>
Took the random function UniqueRandomNumbersWithinRange from Generating UNIQUE Random Numbers within a range - PHP
<?php
function UniqueRandomNumbersWithinRange($min, $max, $quantity) {
$numbers = range($min, $max);
shuffle($numbers);
$arr = array_slice($numbers, 0, $quantity);
sort($arr);
return $arr;
}
$chkArr = array();
$rand = UniqueRandomNumbersWithinRange(0, 100, 10);
$rIdx = 0;
for($k=0; $k<100; $k++){
$caseid1 = $task1 = $asin1 = $sla1 = $associate1 = $quer = "";
${"caseid".$k}=mysql_result($ticket,$k, "case_id");
${"task".$k}=mysql_result($ticket,$k, "sub_issue");
${"asin".$k}=mysql_result($ticket,$k, "asin");
${"vendor_credit".$k}=mysql_result($ticket,$k, "vendor_credit");
${"create_date".$k}=mysql_result($ticket,$k, "create_date");
${"resolve_date".$k}=mysql_result($ticket,$k, "resolve_date");
${"root_cause".$k}=mysql_result($ticket,$k, "root_cause");
${"associate".$k}=mysql_result($ticket,$k, "associate");
$chk = '';
if( in_array($k, $rand) )
$chk = "checked";
array_push($chkArr, "<tr>"."<th>"."<input type='checkbox' ".$chk ." value='${'caseid'.$k}' name='checkboxvar[]'>"."</th>"."<th>".${'caseid'.$k}."</th>"."<th>".${'task'.$k}."</th>"."<th>".${'asin'.$k}."</th>"."<th>".${'vendor_credit'.$k}."</th>"."<th>".${'create_date'.$k}."</th>"."<th>".${'resolve_date'.$k}."</th>"."<th>".${'root_cause'.$k}."</th>"."</tr>");
}
echo implode($chkArr);
?>

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.

Can each row in an HTML table be numbered?

What I would like to do is number each row in my table. I can't manually number the table myself, as all of the info in it is retrieved from a database. Is this possible with jQuery or PHP? Here's a screen shot of the table:
I tried searching for this, and did not find anything that helped me.
Here is the PHP / HTML that is displaying the table:
<tr>
<th>Name</th>
<th>Email</th>
<th>Subject</th>
<th>Created on</th>
<th style="width:65px;">Status</th>
<th>Actions</th>
</tr>
<?php
[...]
//Display the results
while($info = mysql_fetch_assoc($result)){
//data
$name = $info['name'];
$email = $info['email'];
$subject = $info['subject'];
$ticketid = $info['ticket'];
$isActive = $info['is_active'];
$created = $info['created'];
//status
if($isActive == "1") {
$status = "<span class=\"open\">Open</span>";
$status2 = "active";
}
else if($isActive == "0") {
$status = "<span class=\"closed\">Closed</span>";
$status2 = "closed";
}
else {
$status = "";
}
echo "
<tr>
<td style=\"min-width: 87px;\">$name</td>
<td style=\"min-width:248px;\" title=\"$email\">".addEllipsis($email, 33)."</td>
<td title=\"$subject\">".addEllipsis($subject, 18)."</td>
<td style=\"width: 235px;\">$created</td>
<td title=\"This ticket is $status2\">$status</td>
<td><a href='/employee/employee.php?ticket=$ticketid'>View Ticket »</a></td>
</tr>
";
}
As you can see, it's displayed with a while loop.
If anyone knows a way to number each line in my table with jQuery or PHP, please help me :)
$trCounter=0;
while($info = mysql_fetch_assoc($result)){
//data
$name = $info['name'];
$email = $info['email'];
$subject = $info['subject'];
$ticketid = $info['ticket'];
$isActive = $info['is_active'];
$created = $info['created'];
//status
if($isActive == "1") {
$status = "<span class=\"open\">Open</span>";
$status2 = "active";
}
else if($isActive == "0") {
$status = "<span class=\"closed\">Closed</span>";
$status2 = "closed";
}
else {
$status = "";
}
echo "
<tr>
<td>$trCounter++</td>
<td style=\"min-width: 87px;\">$name</td>
<td style=\"min-width:248px;\" title=\"$email\">".addEllipsis($email, 33)."</td>
<td title=\"$subject\">".addEllipsis($subject, 18)."</td>
<td style=\"width: 235px;\">$created</td>
<td title=\"This ticket is $status2\">$status</td>
<td><a href='/employee/employee.php?ticket=$ticketid'>View Ticket »</a></td>
</tr>
";
}
or you could always use the :eq api in your jquery selector or its equivalent to work with the index but like I asked it depends on what you want to do with the index.
I would go with PHP solution listed by Atul Gupta.
To add more - you also can to start iteration based on which page you are.
<?php
$i = ($page-1) * $itemsPerPage;
while(....)
{
echo $i;
$i++;
}
?>
if you are on the second page of your list would get something like 11,12,13,14,....
jQuery:
$(function () {
var i = 0;
$('table thead tr').prepend('<th>#</th>');
$('table tbody tr').each(function () {
i += 1;
$(this).prepend('<td>' + i + '</td>');
});
});
PHP
<tr>
<th>Sr. No</th> // Add header for counter
<th>Name</th>
...
</tr>
...
$i=1; // add counter -----------corrected-------------
while($info = mysql_fetch_assoc($result)){
//data
...
echo "
<tr>
<td>$i</td> // include counter to table
<td style=\"min-width: 87px;\">$name</td>
...
</tr>
";
$i++; // increment counter
}
Set an auto increment property in the SQL table, which can be used as an index, and will increase automatically when a new entry is added?

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
}
?>

Categories