Writing nice sentences even if one value is missing [closed] - php

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I'm really tired of making "if elseif else" statements do you know a fun way to deal with this :
For the purpose of this example I'll focused on 3 variables but in reallity there are more than 500.
Required variables :
name
Those variables can be empty :
birthdate, city
I want to write a sentence like that :
The user John Doe who is 35 aged and leave in Pittsburg.
But if the birthdate is empty I want to write :
The user John Doe leave in Pittsburg.
And so on....
You can see the expected output and the real array of values here :
http://jsfiddle.net/CMC8a/1/
I tried multiple ways to approach this issue see more here :
<style>
*{
font-family: Helvetica;
}
label{
font-size: large;
}
</style>
<table id="entete">
</table>
<h2><?php echo $data['patient']['nom']['value'] ?> <?php echo $data['patient']['prenom']['value'] ?> <?php echo age_count($data['patient']['ddn']['value']) ?> ans</h2>
<?php
$blocInfoGenerales = new BlocColumnPdf(
'Informations générales', array(
$data['patient']['ddn'],
$data['patient']['sexe'],
$data['patient']['profession'],
$data['patient']['villeNaissance']
, $data['patient']['departement'])
, 2
);
$blocInfoGenerales->render();
?>
<h3>Antécédents personnels</h3>
<table>
<tr>
<td><label>Respiratoires : </label><?php echo makeCommaForThoseMCB(array($data['N1']['asthme'], $data['N1']['rhinite'], $data['N1']['bcpo'], $data['N1']['insuffisanceResp'], $data['N1']['chirurgieOrl'], $data['N1']['autreChirurgie'], $data['N1']['allergies'], $data['N1']['old'])) ?></td>
</tr>
<tr>
<td><label>Cardio-vasculaires et cérébraux : </label><?php echo makeCommaForThoseMCB(array($data['N1']['hypertensionArterielle'], $data['N1']['infarctusMyocarde'], $data['N1']['bcpo'], $data['N1']['insuffisanceCoronaire'], $data['N1']['troubleRythme'], $data['N1']['accidentVasculaireCerebral'], $data['N1']['insuffisanceCardiaque'], $data['N1']['arteriopathie'])) ?></td>
</tr>
<tr>
<td><label>Autres : </label><?php echo makeCommaForThoseMCB(array($data['N1']['tabagismeActuel'], $data['N1']['tabagismeAncien'], $data['N1']['alcool'], $data['N1']['refluxGastro'], $data['N1']['glaucome'], $data['N1']['diabete'], $data['N1']['hypercholesterolemie'], $data['N1']['hypertriglyceridemie'], $data['N1']['dysthyroidie'], $data['N1']['depression'])) ?></td>
</tr>
<tr>
<td><label>Antécédents familiaux : </label><?php echo makeCommaForThoseMCB(array($data['N1']['sedentarite'], $data['N1']['syndromeDApneesSommeil'], $data['N1']['obesite'], $data['N1']['dysmorphieFaciale'])) ?></td>
</tr>
</table>
<h3>Traitements en cours</h3>
<table>
<tr>
<td><?php echo makeCommaforThisVMB($data['N1']['vidalMultiBox'], 'vidalMultiBox') ?></td>
</tr>
</table>
<h3>Première visite</h3>
<table>
<tr>
<td>
<?php echo makeCommaForThoseFields(array($data['suivi1'][0]['dateVisite'], $data['suivi1'][0]['adressePar'], $data['suivi1'][0]['selecMedecinSpecialiste'])) ?>
</td>
</tr>
<tr>
<td>
<?php echo makeCommaForThoseFields(array($data['suivi1'][0]['motifConsultation'])) ?>
</td>
</tr>
<tr>
<td>
<?php echo makeCommaForThoseFields(array($data['suivi1'][0]['taille'], $data['suivi1'][0]['poids'], $data['suivi1'][0]['perimetreCervical'], $data['suivi1'][0]['perimetreAbdominal'])) ?>
</td>
</tr>
<tr>
<td>
<?php echo makeCommaForThoseFields(array($data['suivi1'][0]['PASystolique'], $data['suivi1'][0]['PADiastolique'])) ?>
</td>
</tr>
<tr>
<td><label> <?php echo makeCommaForThoseMCB(array($data['suivi1'][0]['profilMaxilofacial'])) ?></label></td>
</tr>
<tr>
<td>
<?php echo makeCommaForThoseFields(array($data['suivi1'][0]['autoPASystolique'], $data['suivi1'][0]['autoPADiastolique'])) ?>
</td>
</tr>
<tr>
<td>
<label>Bilan Biologique :</label>
<?php
echo makeCommaForThoseFields(array(
$data['suivi1'][0]['dateBilan'], $data['suivi1'][0]['glycemie'],
$data['suivi1'][0]['cholesterolemieTotale'], $data['suivi1'][0]['HDL'],
$data['suivi1'][0]['LDL'], $data['suivi1'][0]['triglycerides']
))
?>
</td>
</tr>
<tr>
<td><label>Clinique :</label> <?php
echo makeCommaForThoseMCB(
array(
$data['suivi1'][0]['ronflements'],
$data['suivi1'][0]['somnolenceDiurne'],
$data['suivi1'][0]['somnolenceConduite'],
$data['suivi1'][0]['fatigueMatinale'],
$data['suivi1'][0]['cephaleesMatinales'],
$data['suivi1'][0]['troubleLibido'],
$data['suivi1'][0]['troubleMemoire'],
$data['suivi1'][0]['troubleErection'],
$data['suivi1'][0]['transpirationNocturne']
))
?>
</td>
</tr>
<tr>
<td><label>Auto-questionnaires :</label> <?php
echo makeCommaForThoseFields(
array(
$data['suivi1'][0]['echelleEpworth'],
$data['suivi1'][0]['echellePichot'],
$data['suivi1'][0]['echelleDepression'],
$data['suivi1'][0]['SJSRCriteresDiagnostiques']
))
?>
</td>
</tr>
<tr>
<?php $data['suivi1'][0]['estimationDureeMoyenneDeSommeil']['label'] = 'Estimation durée moyenne de sommeil' ?>
<td><?php echo makeCommaForThoseFields(array($data['suivi1'][0]['estimationDureeMoyenneDeSommeil'] )) ?></td>
</tr>
<tr>
<td>
<label>Exploration fonctionnelle respiratoire :</label>
<?php
echo makeCommaForThoseFields(array(
$data['suivi1'][0]['dateBilan'], $data['suivi1'][0]['glycemie'],
$data['suivi1'][0]['cholesterolemieTotale'], $data['suivi1'][0]['HDL'],
$data['suivi1'][0]['LDL'], $data['suivi1'][0]['triglycerides']
))
?>
</td>
</tr>
</table>
<?php
function count_capitals($s) {
return strlen(preg_replace('![^A-Z]+!', '', $s));
}
function custom_strtolower($string) {
if (count_capitals($string) <= 1) {
return strtolower($string);
}
return $string;
}
function makeCommaForThoseFields($elements) {
$i = 0;
$response = false;
foreach ($elements as $element) {
if ($element['value']) {
if ($i == 0) {
$response = '<label>' . $element['label'] . '</label> : ';
$response .= (isset($element['libelle'])) ? custom_strtolower($element['libelle']) : $element['value'];
$response .= (isset($element['unit'])&& $element['unit'] != 'NULL') ? ' ' . ($element['unit']) : '';
} else {
if ($element['label'] != 'Préciser' && $element['label'] != 'Préciser') {
$response .= ', <label>' . custom_strtolower($element['label']) . '</label> : ';
$response .= (isset($element['libelle'])) ? custom_strtolower($element['libelle']) : $element['value'];
$response .= (isset($element['unit'])&& $element['unit'] != 'NULL') ? ' ' . ($element['unit']) : '';
} else {
$response .= ' (';
$response .= (isset($element['libelle'])) ? custom_strtolower($element['libelle']) : $element['value'];
$response .= (isset($element['unit']) && $element['unit'] != 'NULL') ? ' ' . ($element['unit']) : '';
$response .= ')';
}
}
$i++;
}
}
if ($response) {
$response.='.';
}
return $response;
}
function makeCommaforThisVMB($vidalMultiBox, $key) {
$i = 0;
$response = false;
foreach ($vidalMultiBox as $element) {
$response = $element[$key . '_libelle'] . ' ' . $element[$key . '_val_posologie'] . ' ' . $element[$key . '_id_posologie'] . ', ';
}
if ($response) {
$response = substr($response, 0, -2);
$response.='.';
}
return $response;
}
function makeCommaForThoseMCB($elements) {
$i = 0;
$response = false;
foreach ($elements as $element) {
if ($element['value'] == 1) {
if ($i == 0) {
$response = $element['label'];
} else {
$response.= ', ' . strtolower($element['label']);
}
$i++;
}
}
if ($response) {
$response.='.';
}
return $response;
}
class BlocColumnPdf {
private $m_title;
private $elements;
private $m_colone;
private $m_id;
function __construct($title, $p_elements, $p_colone, $id) {
$this->m_title = $title;
foreach ($p_elements as $e) {
$tmp_e = new ElementColumnPdf($e);
if (!$tmp_e->isEmpty()) {
$this->elements[] = $tmp_e;
}
}
$this->m_colone = $p_colone;
return $this;
}
function render() {
$is_empty = true;
foreach ($this->elements as $e) {
if (!$e->isEmpty()) {
$is_empty = false;
break;
}
}
if (!$is_empty) {
echo '<h3>' . $this->m_title . '</h3>';
echo '<table id="' . $this->m_id . '">';
$lines_elements = array_chunk($this->elements, $this->m_colone);
foreach ($lines_elements as $line_elements) {
$this->renderLine($line_elements);
}
echo '</table>';
}
}
function renderLine($elements) {
foreach ($elements as $e) {
if (!$e->isEmpty()) {
$is_empty = false;
break;
}
}
if (!$is_empty) {
echo '<tr>';
foreach ($elements as $e) {
$e->render();
}
echo '</tr>';
}
}
}
class ElementColumnPdf {
private $element;
function __construct($p_element) {
$this->element = $p_element;
return $this;
}
function render() {
$text = (isset($this->element['libelle']) && $this->element['libelle']) ? $this->element['libelle'] : $this->element['value'];
$unit = (isset($this->element['unit']) && $this->element['unit']) ? $this->element['unit'] : '';
if (!$this->isEmpty()) {
echo '<td><label>' . $this->element['label'] . '</label> <span class="value">' . $text . '</span><span class="unit">' . $unit . '</span></td>';
} else {
echo '<td></td>';
}
}
function isEmpty() {
if ($this->element['value']) {
return false;
}
return true;
}
}
The use and abuse of is because of the tool I'm using to convert HTML to PDF. this tool is doing better with table rather than div
What would you do ?

This is actually a potentially interesting question.
What you need to do, ideally, is create an array of "things" to say about the person, then make a human-readable list of facts.
Something like this could work well:
$things = array();
if( !empty($birthdate)) $things[] = "who is aged ".$birthdate;
if( !empty($city)) $things[] = "lives in ".$city;
Then output it:
echo "The user ".$name;
if( $things) { // check that there are actually things to say
$lastthing = array_pop($things);
if( $things) { // see if there are still things, ie. there were at least two
echo implode(", ",$things);
echo " and ";
}
echo $lastthing;
}
The above structure results in grammatically correct lists, based on the number of items:
A
A and B
A, B and C
A, B, C and D
[and so on]

Related

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.

Dynamically generate table using PHP

I know this has been asked before and I have got it working using the following code:
<?php
$maxcols = 8; $i = 0;
echo "<table id='table1'><tr>";
foreach ($id as $k => $v) {
echo "<td id='0'><div id='{$k}' class='drag t1'>{$v}</div></td>"; $i++;
if ($i == $maxcols) { $i = 0; echo "</tr><tr>"; }
} $i++;
while ($i <= $maxcols) {
$i++; echo "<td></td>";
}
echo "</tr></table>";
?>
This results in a table that looks like this :
I'd like to add headers to this so the end result looks like this:
I'd like to do it dynamically so if I create a table that is only 5 columns wide I'd get on the first header row ID01 - ID05 and on the second header row ID06 - ID10
I want to limit the header ID values to be no more than $maxid any extra header fields should be blank, like this : If $maxid = 12; then :
I need the header rows are made as follows and not using <TH>
<td class="mark">
I'm using some javascript to allow the movement of cell data.
The class is used to set the formatting on the header and stop items from being dragged into the fields.
Can anyone point me in the right direction on how to do this.
This should help you.
$maxcols = 8;
$maxid = 12;
$startid = 1;
echo "<table id='table1'>\n";
for ($i = 1;$i<=ceil($maxid/$maxcols);$i++) {
echo "<tr>\n";
for ($j=1;$j<=$maxcols;$j++)
if ($startid <= $maxid)
echo " <td class='mark'>ID".$startid++."</td>\n";
else
echo " <td> </td>\n";
echo "</tr>\n<tr>\n";
for ($j=1;$j<=$maxcols;$j++)
echo "<td>Content</td>\n";
echo "</tr>\n";
}
echo "</table>\n";
Generates
<table id='table1'>
<tr>
<td class='mark'>ID1</td>
<td class='mark'>ID2</td>
<td class='mark'>ID3</td>
<td class='mark'>ID4</td>
<td class='mark'>ID5</td>
<td class='mark'>ID6</td>
<td class='mark'>ID7</td>
<td class='mark'>ID8</td>
</tr>
<tr>
<td>Content</td>
<td>Content</td>
<td>Content</td>
<td>Content</td>
<td>Content</td>
<td>Content</td>
<td>Content</td>
<td>Content</td>
</tr>
<tr>
<td class='mark'>ID9</td>
<td class='mark'>ID10</td>
<td class='mark'>ID11</td>
<td class='mark'>ID12</td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>Content</td>
<td>Content</td>
<td>Content</td>
<td>Content</td>
<td>Content</td>
<td>Content</td>
<td>Content</td>
<td>Content</td>
</tr>
</table>
try this. It will work in the same way as you desired
<?php
$id= array("1","2","3","4","5","6","7","8","9","10","11","12");
$maxcols = 8; $i = 0;$j=0;$t=0;$s=0;
$maxid = count($id);
echo "<table id='table1'><tr>";
foreach ($id as $k => $v)
{
if($t == 0)
{
while ($t <= $maxcols-1) {
if($s < $maxid)
{
$s++;$t++; echo "<td class='mark'>id$s</td>";
}
else
{
echo "<td class='mark'></td>";$t++;$s++;
}
}
echo "</tr><tr>";
}
else
{
}
echo "<td id='0'><div id='{$k}' class='drag t1'>{$v}</div></td>"; $i++;
if ($i == $maxcols)
{
echo "</tr><tr>";
if($j == 0)
{
while ($j <= $maxcols-1) {
if($s < $maxid)
{
$s++;$j++; echo "<td class='mark'>id$s</td>";
}
else
{
echo "<td class='mark'></td>";$j++;$s++;
}
}
echo "</tr><tr>";
}
$i=0;
}
}
echo "</tr></table>";
?>
Output
Hi You can Use My Library:
class generate{
private $row = "<tr>{columns}</tr>";
private $td = "<td {attr}>{data}</td>";
private $attributeTR="";
private $attributeTD="";
private $tdBuilder="";
public function addCol($ColumValsArr=array("class='motota'"=>"Example")){
foreach($ColumValsArr as $key=>$val){
$newCol = str_replace("{data}",$val,$this->td);
$newCol = str_replace("{attr}",$key,$newCol);
$this->tdBuilder .= str_replace("{data}",$key,$newCol);
}
}
public function getRow(){
return str_replace("{columns}",$this->tdBuilder,$this->row);
}
}
<?php
function TableFunc($Data)
{
$Table = "<table>" . PHP_EOL;
foreach ($Data as $tags => $array) {
$Table .= "<$tags>" . PHP_EOL;
foreach ($array as $thead) {
$tag=$tags==="tbody"?"td":"th";
$Table .= "<tr>" . PHP_EOL;
if (is_array($thead)) {
foreach ($thead as $theadItem) {
if (is_array($theadItem))
$Table .= "<$tag colspan='$theadItem[1]'>$theadItem[0]</$tag>" . PHP_EOL;
else
$Table .= "<$tag>$theadItem</$tag>" . PHP_EOL;
}
}
$Table .= "</tr>" . PHP_EOL;
}
$Table .= "</$tags>" . PHP_EOL;
}
$Table .= "</table>" . PHP_EOL;
return $Table;
}
$Data = array(
"thead" => [
[["GENEL BİLGİ", 2], ["KALORİMETRE (ISINMA)", 2], ["HESAPLAMA", 2]],
["NO", "AD SOYAD", "FARK", "TUTAR", "OKUMA", "ÖDENECEK"]
],
"tbody"=>array(
array("1","MURAT DURAN","100","100.00","10.00","110.00"),
array("1","MURAT DURAN","100","100.00","10.00","110.00"),
array("1","MURAT DURAN","100","100.00","10.00","110.00"),
array("1","MURAT DURAN","100","100.00","10.00","110.00"),
),
"tfoot" => [["NO", "AD SOYAD", "M2", "MAHSUP", "SAYAÇ", "15°", "FARK", "TUTAR", "ORTAK ALAN", "EKSTRA", "MUAFİYET", "OKUMA", "ÖDENECEK"]]
);
echo TableFunc($Data);

Issues with Pagination in PHP

Currently I've 2 tables and have the datas are dynamic.
I need to add pagination for both tables seperately. I had added paginator using paginator class and it is working fine. But the problem is when I click on the next button of the first table then the contents of both tables are changed in to the next page.
Paginator.php
<?php
// Paginator Class
// error_reporting(E_ALL);
define("QS_VAR", "page"); // the variable name inside the query string (don't use this name inside other links)
define("STR_FWD", "Next>>"); // the string is used for a link (step forward)
define("STR_BWD", "<<Prev"); // the string is used for a link (step backward)
$scriptname = (isset($_SERVER['SCRIPT_NAME']) ? $_SERVER['SCRIPT_NAME'] : '');
define("SCRIPT_NAME", $scriptname);
$v = (isset($_REQUEST['page_num_rows']) ? (is_numeric($_REQUEST['page_num_rows']) ? $_REQUEST['page_num_rows'] : 5) : 5);
define("NUM_ROWS", $v); // the number of records on each page
class Paginator {
var $sql;
var $result;
var $get_var = QS_VAR;
var $rows_on_page = NUM_ROWS;
var $str_forward = STR_FWD;
var $str_backward = STR_BWD;
var $all_rows;
var $num_rows;
var $page;
var $number_pages;
var $url_name = SCRIPT_NAME;
// constructor
function Paginator() {
}
// sets the current page number
function set_page() {
$this->page = (isset($_REQUEST[$this->get_var]) && $_REQUEST[$this->get_var] != "") ? $_REQUEST[$this->get_var] : 0;
return $this->page;
}
// gets the total number of records
function get_total_rows() {
$tmp_result = mysql_query($this->sql);
$this->all_rows = mysql_num_rows($tmp_result);
mysql_free_result($tmp_result);
return $this->all_rows;
}
// get the totale number of result pages
function get_num_pages() {
$this->number_pages = ceil($this->get_total_rows() / $this->rows_on_page);
return $this->number_pages;
}
// returns the records for the current page
function get_page_result() {
$start = $this->set_page() * $this->rows_on_page;
$page_sql = sprintf("%s LIMIT %s, %s", $this->sql, $start, $this->rows_on_page);
$this->result = mysql_query($page_sql);
return $this->result;
}
// get the number of rows on the current page
function get_page_num_rows() {
$this->num_rows = #mysql_num_rows($this->result);
return $this->num_rows;
}
// free the database result
function free_page_result() {
#mysql_free_result($this->result);
}
function display_row_count() {
$var = $this->get_var;
$url_part1 = $this->url_name . "?";
$url_part2 = "&" . $var . "=0" . $this->rebuild_qs($var);
$select = " Show ";
$select.="<form method=get name=page_num_rows_form action=\"$this->url_name\" >"; // [form used for javascript disabled case] -not working
$select.="<select name=page_num_rows id=page_num_rows onChange=\"window.location='$url_part1'+'page_num_rows='+this.value+'$url_part2'\" >";
$select.="<option value=50 " . (isset($_REQUEST['page_num_rows']) ? ($_REQUEST['page_num_rows'] == 50 ? ' selected ' : '') : '') . " >50</option>";
$select.="<option value=100 " . (isset($_REQUEST['page_num_rows']) ? ($_REQUEST['page_num_rows'] == 100 ? ' selected ' : '') : '') . " >100</option>";
$select.="<option value=150 " . (isset($_REQUEST['page_num_rows']) ? ($_REQUEST['page_num_rows'] == 150 ? ' selected ' : '') : '') . " >150</option>";
$select.="<option value=200 " . (isset($_REQUEST['page_num_rows']) ? ($_REQUEST['page_num_rows'] == 200 ? ' selected ' : '') : '') . " >200</option>";
$select.="<option value=500 " . (isset($_REQUEST['page_num_rows']) ? ($_REQUEST['page_num_rows'] == 500 ? ' selected ' : '') : '') . " >500</option>";
$select.="</select>";
$select.="<noscript> <input type=submit value=Go /></noscript>";
$select.="</form>"; // form used for javascript disabled case -- not working
$select.=" per page";
return $select;
}
// function to handle other querystring than the page variable
function rebuild_qs($curr_var) {
if (!empty($_SERVER['QUERY_STRING'])) {
$parts = explode("&", $_SERVER['QUERY_STRING']);
$newParts = array();
foreach ($parts as $val) {
if (stristr($val, $curr_var) == false) {
array_push($newParts, $val);
}
}
if (count($newParts) != 0) {
$qs = "&" . implode("&", $newParts);
} else {
return false;
}
return $qs; // this is your new created query string
} else {
return false;
}
}
// this method will return the navigation links for the conplete recordset
function navigation($separator = " | ", $css_current = "", $back_forward = false) {
$max_links = NUM_LINKS;
$curr_pages = $this->set_page();
$all_pages = $this->get_num_pages() - 1;
$var = $this->get_var;
$navi_string = "";
if (!$back_forward) {
$max_links = ($max_links < 2) ? 2 : $max_links;
}
if ($curr_pages <= $all_pages && $curr_pages >= 0) {
if ($curr_pages > ceil($max_links / 2)) {
$start = ($curr_pages - ceil($max_links / 2) > 0) ? $curr_pages - ceil($max_links / 2) : 1;
$end = $curr_pages + ceil($max_links / 2);
if ($end >= $all_pages) {
$end = $all_pages + 1;
$start = ($all_pages - ($max_links - 1) > 0) ? $all_pages - ($max_links - 1) : 1;
}
} else {
$start = 0;
$end = ($all_pages >= $max_links) ? $max_links : $all_pages + 1;
}
if ($all_pages >= 1) {
$forward = $curr_pages + 1;
$backward = $curr_pages - 1;
$navi_string = ($curr_pages > 0) ? "" . $this->str_first . " " . $this->str_backward . " " : $this->str_first . " " . $this->str_backward . " ";
$navi_string .= ($curr_pages < $all_pages) ? " " . $this->str_forward . "" . " " : " " . $this->str_forward . " ";
}
}
return "<span style='font-size:.7em; padding:3px 3px 4px 3px;'>" . $this->current_page_info() . $navi_string . "</span>";
}
function current_page_info() {
$cur_page = $this->set_page() + 1;
$total_pages = $this->get_num_pages();
// $page_info = " Page " . $cur_page . " of " . $total_pages . " ";
// return $page_info;
}
function show_go_to_page() {
$cur_page = $this->set_page() + 1;
$total_pages = $this->get_num_pages();
$options = "";
for ($i = 1; $i <= $total_pages; $i++) {
$options.="<option value=$i " . (($i == $cur_page) ? ' selected ' : '') . ">$i</option>";
}
$page_info = " Go to page <input type=text name=paginator_go_to_page id=paginator_go_to_page size=1 value=$cur_page />";
// $page_info.= "<select name=paginator_go_to_page2 >$options</select>";
return $page_info;
}
}
?>
tables.php
<?php
include("library/paginator.php");
?>
<div style="text-align:right;">
<?
$query = "select * from haves_settings";
$tab = mysql_query($query);
$row = mysql_fetch_array($tab);
$item_no = $row['items_to_show'];
$scroll = $row['scroll_interval'];
$online_paginate = new Paginator;
$online_paginate->sql = "select * from placing_item_bid where status='Active' and picture1!='' and selling_method!='want_it_now' and selling_method!='ads' and bid_starting_date <= now() and expire_date>=now() order by item_id desc"; // sql statement
$online_paginate->rows_on_page = $item_no;
$results = $online_paginate->get_page_result(); // result set
$num_rows = $online_paginate->get_page_num_rows(); // number of records in result set
$nav_links = $online_paginate->navigation(" | "); // the navigation links (define a CSS class
?>
</div>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr bgcolor="#d79196" class="detail9txt">
<input type="hidden" value="2" name="len">
<td align="center" width="20%"><b>Picture</b> </td>
<td width="30%" align="center"><b>Name / Responses</b> </td>
<td width="50%" align="center"><b>Description</b> </td>
</tr><tr style="height:10px;"><td></td></tr>
<?
if ($num_rows > 0) {
while ($bestsellers_fetch = mysql_fetch_array($results)) {
$temp = $bestsellers_fetch['item_id'];
$sql = "SELECT count(`user_id`) as response FROM `watch_list` where `item_id`=$temp group by `item_id`";
$res = mysql_query($sql);
$response = mysql_fetch_row($res);
$counttop = $counttop + 1;
if (!empty($bestsellers_fetch['sub_title']))
$item_subtitle1 = $bestsellers_fetch['sub_title'];
else
$item_subtitle1 = substr($bestsellers_fetch['item_title'], 0, 20);
$item_title1 = substr($bestsellers_fetch['item_title'], 0, 40)
?>
<tr>
<td class="tr_botborder" style="vertical-align:middle;" width="20%" align="center"><div align="center"><img src="thumbnail/<?= $bestsellers_fetch['picture1']; ?>" alt="" width="79" height="70" border="0" /></div></td>
<td class="tr_botborder" style="vertical-align:middle;" width="30%" align="center"><div align="center"><span class="bestsellerstxt"><?= $item_subtitle1; ?> <?= $item_title1; ?><br/><?php if ($response[0] != '') { ?><a style="text-decoration:none;color:#336666;" href="detail.php?item_id=<?= $bestsellers_fetch['item_id']; ?>"> <?php echo $response[0] . ' responses'; ?></a> <?php } else { ?><span style="color:#666666;"><?php
echo '0 responses';
}
?></span></span></td>
<td class="tr_botborder" style="vertical-align:middle;" width="50%" align="center"><div align="center"><span class="bestsellerstxt"><?= html_entity_decode($bestsellers_fetch['detailed_descrip']); ?></span></td>
</tr>
<?
if ($counttop != 2) {
}
}
} else {
?>
<tr><td height="148" align="center" class="featxt">No Items Available</td></tr>
<?
}
?>
</table>
<div style="text-align: right;"><?php echo $nav_links; ?></div>
//wants content
$online_paginate1 = new Paginator;
$online_paginate1->sql = "select * from placing_item_bid where status='Active' and selling_method='want_it_now' order by item_id desc";
$online_paginate1->rows_on_page = $item_no1;
$result1 = $online_paginate1->get_page_result(); // result set
$want_total_records = $online_paginate1->get_page_num_rows(); // number of records in result set
$nav_links1 = $online_paginate1->navigation(" | "); // the navigation links (define a CSS class
?>
<div class="superbg">
<table cellspacing="0" cellpadding="5" width=100%>
<form name="want_form" action="myauction.php" method=post>
<tr bgcolor="#d79196" class="detail9txt">
<input type="hidden" name="len" value="<?= $want_total_records ?>">
<td align="center" width="30%"><b>Name / Responses</b> </td>
<td align="center" width="20%"><b>Picture</b> </td>
<td width="50%" align="center"><b>Description</b> </td>
</tr>
<?
if ($want_total_records > 0) {
while ($want_row = mysql_fetch_array($result1)) {
$tot_bid_sql = "select count(*) from want_it_now where wanted_itemid=" . $want_row[item_id];
$tot_bid_res = mysql_query($tot_bid_sql);
$tot_bids = mysql_fetch_array($tot_bid_res);
?>
<tr class="detail9txt">
<td class="tr_botborder" align="center" style="vertical-align:middle;" width="30%">
<a href="wantitnowdes.php?item_id=<?= $want_row['item_id'] ?>" class="header_text">
<? echo $want_row['item_title']; ?></a> <br/> <?
if ($tot_bids[0] != 0) {
?>
<a style="font-weight:normal;" href="wantitnowdes.php?item_id=<?= $want_row['item_id'] ?> " class="header_text"><? echo $tot_bids[0] . ' responses'; ?></a>
<?
} else {
echo $tot_bids[0] . ' responses';
}
?></td>
<td class="tr_botborder" style="vertical-align:middle;" width="20%" align="center">
<?
if (!empty($want_row['picture1'])) {
$img = $want_row['picture1'];
list($width, $height, $type, $attr) = getimagesize("images/$img");
$h = $height;
$w = $width;
if ($h > 50) {
$nh = 50;
$nw = ($w / $h) * $nh;
$h = $nh;
$w = $nw;
}
if ($w > 50) {
$nw = 50;
$nh = ($h / $w) * $nw;
$h = $nh;
$w = $nw;
}
?>
<!-- <img name="runimg" src="images/<? //echo $want_row['picture1']; ?>" border=1 width=<? //= $w; ?> height=<? //=$h ?> >-->
<img name="runimg" src="images/<? echo $want_row['picture1']; ?>" border=1 width="79" height="70" >
<?
} else {
?>
<img src="images/no_image.gif" border=1 name="runimg" >
<? } ?>
</td>
<td class="tr_botborder" style="vertical-align:middle;" width="50%" align="center"><div align="center"><span class="bestsellerstxt"><?= html_entity_decode($want_row['detailed_descrip']); ?></span></td>
</tr>
<?
} // while
} else {
?>
<tr>
<td width="3%"> </td>
<td width="97%" class="myauction3txt">There are no items in this section</td>
</tr>
<? } ?>
</table>
<div style="text-align: right;"><?php echo $nav_links1; ?></div>
</div>
Where is the problem ?
Paginator class uses the same query string "page" parameter to calculate the current page. If you add 2 or more Pagination in the same request, "page" will be shared by all instances, leading to this mess you described.
How to fix it ?
Tell the Paginator class which parameter to use in query string... follow this 2-step patch below :
Step 1 : replace constructor in Paginator class
// constructor
function Paginator($get_var=null) {
if ($get_var!=null) $this->get_var = $get_var;
}
Step 2 : update Paginator object creation (twice)
$online_paginate = new Paginator('page_table1');
and later :
$online_paginate1 = new Paginator('page_table2');
Hope this helps !

Nested Key-Value lookups in php

I am trying to make a "stock" website for a class at school, and it's my first dive into php. Basically, the script pulls down a CSV file form a google docs spreadsheet, and (attempts) to put the values into an array for use later. I'd like to show the top 5 rising and falling stocks, but am having issues. Here's main section of the script:
<html>
<head>
<?php
#Global Variables
$rising = array();
$falling = array();
$stocks = array();
#End Global Variables
#Function to read data from the spreadsheet
function get_data($url){
$ch = curl_init();
$timeout = 5;
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
#Process data
function populateTicker(){
$document = "https://docs.google.com/spreadsheet/pub?hl=en_US&hl=en_US&key=0AtrtT_MC9_YFdHRDUGx0a2xveXNfOHJVdXJ6bVNkMFE&output=csv";
$data= get_data($document);
$lines = explode("\n", $data);
$val = "";
foreach($lines as $key => $value){
if($key != 0){
$stockInfo = explode(",", $value);
$perChange = $stockInfo[3];
$perChangeVal = "up ";
if($perChange < 0){
$perChangeVal = "down ";
$falling['$stockInfo[0]'] = $perChange;
}else{
$rising['$stockInfo[0]'] = $perChange;
}
$stocks['$stockInfo[0]'] = array("symb" => $stockInfo[0], "name" => $stockInfo[1], "price" => $stockInfo[2]);
$val = $val . "(" . $stockInfo [0] . ") " . $stockInfo [1] . " " . "\$" . $stockInfo [2] . " " . $perChangeVal . $perChange . "% today" . "\v \v \v \v | \v \v \v \v";
}
}
//asort($falling);
//arsort($rising);
return $val;
}
function getRising($index){
if($index <= count($rising)){
$keys = array_keys($rising);
$data = $stocks[$keys[$index]];
return "(" . $data['symb'] . ") " . $data['name'] . " " . "\$" . $data['price'];
}else{
return ".";
}
}
function getFalling($index){
if($index <= count($falling)){
$keys = array_keys($falling);
$data = $stocks[$keys[$index]];
return "(" . $data['symb'] . ") " . $data['name'] . " " . "\$" . $data['price'];
}else{
return ".";
}
}
?>
</head>
<body>
<DIV id='DEBUG'>
<?php
print_r($stocks);
print_r($rising);
print_r($falling);
?>
</DIV>
<center><b><u><font size="+2">Latest Prices</font><br /></u></b></center>
<DIV ID="TICKER" STYLE="border-top:2px solid #CCCCCC; border-bottom:2px solid #CCCCCC; overflow:hidden; width:100%" onmouseover="TICKER_PAUSED=true" onmouseout="TICKER_PAUSED=false">
<?php echo populateTicker(); ?>
</DIV>
<script type="text/javascript" src="webticker_lib.js" language="javascript"></script>
<div id='Top5'>
<br />
<center><b>This page does not update automatically! Please refresh the page to update the information!</b></center>
<br />
<center><b><u><font size="+2">Top 5's</font><br /></u></b></center>
<center>
<table border="1" cellpadding="5">
<tr>
<th>Top 5 Rising</th>
<th>Top 5 Falling</th>
</tr>
<tr>
<td><?php echo getRising(1); ?></td>
<td><?php echo getFalling(1); ?></td>
</tr>
<tr>
<td><?php echo getRising(2); ?></td>
<td><?php echo getFalling(2); ?></td>
</tr> <tr>
<td><?php echo getRising(3); ?></td>
<td><?php echo getFalling(3); ?></td>
</tr> <tr>
<td><?php echo getRising(4); ?></td>
<td><?php echo getFalling(4); ?></td>
</tr> <tr>
<td><?php echo getRising(5); ?></td>
<td><?php echo getFalling(5); ?></td>
</tr>
</table>
</center>
</div>
<br />
<center><b><u><font size="+2">All Stocks</font><br /></u></b></center>
<div id='All'>
<center>
<table border="1" cellpadding="5">
<tr>
<th>Symbol</th>
<th>Name</th>
<th>Price</th>
<th>High</th>
<th>Low</th>
<th>Percent Change</th>
</tr>
<?php
#Dynamic Table Creation
foreach($stocks as $key => $value){
echo '<tr>';
echo '<td>(' . $value['symb'] . ')</td>';
echo '<td>' . $value['name'] . '</td>';
echo '<td>' . $value['price'] . '</td>';
echo '<td></td>';
echo '<td></td>';
echo '<td>' . $vaule['perChange'] . '</td>';
echo '</tr>';
}
?>
</table>
</center>
</div>
</body>
<footer>
</footer>
</html>
But nothing gets assigned to the arrays. Any help would be appreciated.
UPDATE: I added the full source of the front page, index.php
UPDATE2: I figured it out. I come from java, and didn't fully understand how the scope of variables worked in php. A simple
<?php
global $rising, $falling, $stocks;
...
?>
did the trick
I don't know exactly about your code but I can show an example for presenting the nested arrays:
$arr = array('1' => array('1', '2'), '2');
function showNested($array)
{
foreach($array as $key => $value)
{
if(is_array($value))
{
echo $value;
showNested($array);
}
else
{
echo $value;
}
}
}
UPDATE
You used $stocks['$stockInfo[0]'] in your code. I think this kind of syntax would never do anything. Totally when you use a variable in a string, you should surround it by {}. And one thing else that I never tested it before, I don't think putting an array with an index in a string would help the PHP to understand what's the current data in [].

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