HTML, CSS - Display table - php

I'm using HTML tables to display the name of a user, quiz id, and score.
And this is my code.
<?php
echo '<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 5px;
}
</style>';
$data = array();
$userid = 1;
$data[$userid] = array();
$name = 'Davy Jones';
$data[$userid]['name'] = $name;
$quiz = array(
'Qz1' => array(
'easy' => 1,
'normal' => 2,
'hard' => 3,
),
'Qz2' => array(
'easy' => 4,
'normal' => 5,
'hard' => 6,
),
);
$data[$userid]['quizzes'] = $quiz;
echo '<table style="width: 40%">';
echo '<tr>
<td>Name</td>
<td>Easy</td>
<td>Normal</td>
<td>Hard</td>
</tr>
<tr>
<td></td>
<td>Score</td>
<td>Score</td>
<td>Score</td>
</tr>';
foreach ($data as $key => $value) {
$quizzes = $value["quizzes"];
echo $value['name'].'<br>';
foreach ($quizzes as $key => $value2) {
echo $key.' '.$value2['easy'].'<br>';
echo $key.' '.$value2['normal'].'<br>';
echo $key.' '.$value2['hard'].'<br>';
}
}
echo '</table>';
For now I have this type of display.
I don't know how to manipulate the table and get this type of result.
Name Easy Normal Hard
Score Score Score
Qz1 Qz2 Qz1 Qz2 Qz1 Qz2
Davy Jones 1 4 2 5 3 6
Any ideas would be most appreciated.

You could use colspan for the table headings to span them across two columns for the information below them and then echo the appropriate variables and information in the cells:
http://jsfiddle.net/omzc6211/

Try to modify your code this way:
<?php
echo '
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 5px;
}
</style>';
$data = array();
$userid = 1;
$data[$userid] = array();
$name = 'Davy Jones';
$data[$userid]['name'] = $name;
$quiz = array(
'Qz1' => array(
'easy' => 1,
'normal' => 2,
'hard' => 3,
),
'Qz2' => array(
'easy' => 4,
'normal' => 5,
'hard' => 6,
),
);
$data[$userid]['quizzes'] = $quiz;
echo '<table style="width: 40%">';
$quizTypes = array(
'easy',
'normal',
'hard'
);
$colspan = count($quiz);
echo '
<tr>
<td>Name</td>
<td colspan=' . $colspan . '>Easy</td>
<td colspan=' . $colspan . '>Normal</td>
<td colspan=' . $colspan . '>Hard</td>
</tr>
<tr>
<td></td>
<td colspan=' . $colspan . '>Score</td>
<td colspan=' . $colspan . '>Score</td>
<td colspan=' . $colspan . '>Score</td>
</tr>
';
foreach ($data as $user)
{
echo '<tr>';
echo '<td>' . $user['name'] . '</td>';
foreach ($quizTypes as $quizType)
{
foreach ($user["quizzes"] as $quizData)
{
echo '<td>' . (array_key_exists($quizType, $quizData) ? $quizData[$quizType] : '-') . '</td>';
}
}
echo '</tr>';
}
echo '</table>';

As suggested in the accepted answer you should use colspan, but here's the code for your very case:
<?php
echo '<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 5px;
}
</style>';
$data = array();
$userid = 1;
$data[$userid] = array();
$name = 'Davy Jones';
$data[$userid]['name'] = $name;
$quiz = array(
'Qz1' => array(
'easy' => 1,
'normal' => 2,
'hard' => 3,
),
'Qz2' => array(
'easy' => 4,
'normal' => 5,
'hard' => 6,
),
);
$data[$userid]['quizzes'] = $quiz;
echo '<table style="width: 40%">';
echo '<tr>
<td>Name</td>
<td colspan="2">Easy</td>
<td colspan="2">Normal</td>
<td colspan="2">Hard</td>
</tr>
<tr>
<td></td>
<td colspan="2">SCORES</td>
<td colspan="2">SCORES</td>
<td colspan="2">SCORES</td>
</tr>';
foreach ($data as $key => $value) {
$quizzes = $value["quizzes"];
$keys = "";
$easy = "";
$normal = "";
$hard = "";
foreach ($quizzes as $key => $value2) {
$keys .= '<td>'.$key.'</td>';
$easy .= '<td>'.$value2['easy'].'</td>';
$normal .= '<td>'.$value2['normal'].'</td>';
$hard .= '<td>'.$value2['hard'].'</td>';
}
echo '<tr><td></td>' . $keys . $keys . $keys . '</tr>';
echo '<tr><td>'.$value['name'].'</td>' . $easy . $normal . $hard . '</tr></table>';
}
?>

Related

Create a Table With Merged TH Cells

I am creating an Excel download code, in which I am merging the TH cells and looping through TR to put data under specific merged TH.
But all of data is reflecting on first TH row. Below is code:
$K=0;
while($ROW = $RESULT->fetch_assoc() )
{
if($ROW['type'] == $_GET['separate_id'])
{
$DATE[] = $ROW['end_time'];
$meta_values[] = $ROW['meta_values'];
$body = '
<table style="border:1px solid #000; border-collapse:collapse;">
<thead style="border:1px solid #000; padding:8px;width:150px; height:25px;font-size:15px">
';
foreach($DATE as $DATES)
{
$DATESVIEW = explode('T',$DATES);
$body .=' <th colspan="2">'.$DATESVIEW[0].'</th> ';
}
$body .= '
</thead>
';
foreach($meta_values as $VALS)
{
$META_VALS = explode(' | ',$VALS);
foreach($META_VALS as $VALUEs)
{
$REs = explode(' - ', $VALUEs);
$body .= '
<tbody>
<tr style="border:1px solid #000; padding:8px;width:150px; height:25px;font- size:15px">
<td style="border:1px solid #000; padding:8px; width:150px; height:25px;font-size:15px">'.$REs[0].'</td>
<td style="border:1px solid #000; padding:8px; width:150px; height:25px;font-size:15px">'.$REs[1].'</td>
</tr>
</tbody>
';
}
}
}
$K++;
}
$body .= '
</table>
';

Fetch more data inside foreach

So I need to fetch data such as section, item names and subtotal of every section from my database and get the grand total of all the items.
I stumble upon the code below and modify it to my requirements.
The code works perfectly but I need to display more data like Item description, Qty, Price, status and so on.
The code below works and have no problem whatsoever but i need more data (description, qty, price and so on) to display in my table but I can't figure out how to do it.
The data I need to display is also in the same row where projectscostbreakdown_areaname, projectscostbreakdown_itemname and projectscostbreakdown_totalcost are.
<?php
$projectsid = $_GET['projectrfpid'];
$itemdeleted = 1;
$itemfirstothers = 'OTHERS';
$query = $conn->prepare('SELECT projectscostbreakdown_id,
projectscostbreakdown_projectid,
projectscostbreakdown_areaname,
projectscostbreakdown_itemname,
projectscostbreakdown_itemdescription,
projectscostbreakdown_qty,
projectscostbreakdown_costpiece,
projectscostbreakdown_budgeted,
projectscostbreakdown_totalcost,
projectscostbreakdown_note,
projectscostbreakdown_addedby,
projectscostbreakdown_addeddate,
projectscostbreakdown_deleted,
projectscostbreakdown_lastedit,
projectscostbreakdown_lasteditby
FROM projectscostbreakdown WHERE projectscostbreakdown_projectid=:projectsid && projectscostbreakdown_deleted=:itemdeleted ORDER BY projectscostbreakdown_areaname=:itemfirstothers, projectscostbreakdown_areaname ASC, projectscostbreakdown_id DESC');
$query->bindParam(':projectsid', $projectsid, PDO::PARAM_INT);
$query->bindParam(':itemdeleted', $itemdeleted, PDO::PARAM_INT);
$query->bindParam(':itemfirstothers', $itemfirstothers, PDO::PARAM_INT);
$query->execute();
$data = array();
$data2 = array();
$numbering = 0; //for item count
$count = 1; //counter use for background color
while ( $row2 = $query->fetch() ) {
if ( empty($data[ $row2['projectscostbreakdown_areaname'] ]) ) {
$data[ $row2['projectscostbreakdown_areaname'] ]= array();
$data2[ $row2['projectscostbreakdown_itemdescription'] ][ $row2['projectscostbreakdown_qty'] ]= array();
}
if ( empty( $data[ $row2['projectscostbreakdown_areaname'] ][ $row2['projectscostbreakdown_itemname'] ] ) ) {
$data[ $row2['projectscostbreakdown_areaname'] ][ $row2['projectscostbreakdown_itemname'] ] = array();
$data2[ $row2['projectscostbreakdown_itemdescription'] ][ $row2['projectscostbreakdown_qty'] ]= array();
}
$data[ $row2['projectscostbreakdown_areaname'] ][ $row2['projectscostbreakdown_itemname'] ][] = $row2['projectscostbreakdown_totalcost'];
$data2[ $row2['projectscostbreakdown_itemdescription'] ][ $row2['projectscostbreakdown_qty'] ]= array();
}
print '<table width="100%" border="0"><tbody>';
$totalSum = 0;
foreach ( $data as $area => $item ) {
print '<tr style="background-color: white;"><td colspan="7" style="text-align: left;"><br /><br /><b><u>'. $area .'</u></b></td></tr>';
print '<tr style="background-color: #AAAAAA; text-align: center;">
<td width="20%""><b>Item name</b></td>
<td width="30%"><b>Description</b></td>
<td width="5%"><b>Qty.</b></td>
<td width="10%"><b>Cost/Piece</b></td>
<td width="10%"><b>Subtotal</b></td>
<td width="10%"><b>Budget</b></td>
<td width="15%"><b>Note /<br / >Entered by</b></td>
</tr>';
$totalArea = 0;
foreach ( $item as $item => $totalcost ) {
//while ( $data = $query->fetch() ) {
$numbering++;
$count++;
$class = ($count%2 == 0)? 'white': '#CCCCCC';
$sum = array_sum( $totalcost );
print '<tr style="background-color: '.$class.'">';
print '<td style="vertical-align: top; text-align: left;">'. $numbering .'. '. $item . '</td>';
print '<td style="vertical-align: top; text-align: left;">';
print_r($data2);
print '</td>';
print '<td style="vertical-align: top; text-align: right;"></td>';
print '<td style="vertical-align: top; text-align: right;"></td>';
print '<td style="vertical-align: top; text-align: right;">'. number_format($sum, 2,'.', ',') . '</td>';
print '<td style="vertical-align: top; text-align: right;"></td>';
print '<td style="vertical-align: top; text-align: left;"></td>';
print '</tr>';
$totalArea += $sum;
}
print '<tr style="background-color: lightgray; text-align: right;" ><td colspan="6">Section Total: </td><td>'. number_format($totalArea, 2,'.', ',') . '</td></tr>';
$totalSum += $totalArea;
}
print '<tr style="background-color: lightblue; text-align: right;" ><td colspan="6"><b>Grand Total: </b></td><td><b>'. number_format($totalSum, 2,'.', ',') . '</b></td></tr>';
echo '</tbody>
</table>';
?>
UPDATE
The output looks like this right now.
I need to include Description and Qty in the output but cant figure how to be done.
Section1
Item Name-----Description-----Qty-----Subtotal
item 1---------------------------------------------1000
item 2---------------------------------------------2000
----------------------------------Section Total: 3000
Section2
Item Name-----Description-----Qty-----Subtotal
item 3---------------------------------------------1000
----------------------------------Section Total: 1000
------------------------------------Grand Total: 4000
Complete code (more structured, fixed bugs):
<?php
$projectsid = $_GET['projectrfpid'];
$itemdeleted = 1;
$itemfirstothers = 'OTHERS';
$query = $conn->prepare('SELECT projectscostbreakdown_id,
projectscostbreakdown_projectid,
projectscostbreakdown_areaname,
projectscostbreakdown_itemname,
projectscostbreakdown_itemdescription,
projectscostbreakdown_qty,
projectscostbreakdown_costpiece,
projectscostbreakdown_budgeted,
projectscostbreakdown_totalcost,
projectscostbreakdown_note,
projectscostbreakdown_addedby,
projectscostbreakdown_addeddate,
projectscostbreakdown_deleted,
projectscostbreakdown_lastedit,
projectscostbreakdown_lasteditby
FROM projectscostbreakdown WHERE projectscostbreakdown_projectid=:projectsid && projectscostbreakdown_deleted=:itemdeleted ORDER BY projectscostbreakdown_areaname=:itemfirstothers, projectscostbreakdown_areaname ASC, projectscostbreakdown_id DESC');
$query->bindParam(':projectsid', $projectsid, PDO::PARAM_INT);
$query->bindParam(':itemdeleted', $itemdeleted, PDO::PARAM_INT);
$query->bindParam(':itemfirstothers', $itemfirstothers, PDO::PARAM_INT);
$query->execute();
$data = array();
$data2 = array();
$numbering = 0; //for item count
$count = 1; //counter use for background color
$itemData = $query->fetchAll();
$query->execute();
while ($row2 = $query->fetch()) {
if (empty($data[$row2['projectscostbreakdown_areaname']]) ) {
$data[$row2['projectscostbreakdown_areaname']]= array();
$data2[$row2['projectscostbreakdown_itemdescription']][$row2['projectscostbreakdown_qty']] = array();
}
if (empty($data[$row2['projectscostbreakdown_areaname']][$row2['projectscostbreakdown_itemname']])) {
$data[$row2['projectscostbreakdown_areaname']][ $row2['projectscostbreakdown_itemname']] = array();
$data2[$row2['projectscostbreakdown_itemdescription']][$row2['projectscostbreakdown_qty']]= array();
}
$data[$row2['projectscostbreakdown_areaname']][$row2['projectscostbreakdown_itemname']][] = $row2['projectscostbreakdown_totalcost'];
$data2[$row2['projectscostbreakdown_itemdescription']][$row2['projectscostbreakdown_qty']] = array();
}
print '<table width="100%" border="0"><tbody>';
$totalSum = 0;
foreach ( $data as $area => $item ) {
print '<tr style="background-color: white;"><td colspan="7" style="text-align: left;"><br /><br /><b><u>'. $area .'</u></b></td></tr>';
print '<tr style="background-color: #AAAAAA; text-align: center;">
<td width="20%""><b>Item name</b></td>
<td width="30%"><b>Description</b></td>
<td width="5%"><b>Qty.</b></td>
<td width="10%"><b>Cost/Piece</b></td>
<td width="10%"><b>Subtotal</b></td>
<td width="10%"><b>Budget</b></td>
<td width="15%"><b>Note /<br / >Entered by</b></td>
</tr>';
$totalArea = 0;
foreach ( $item as $item => $totalcost ) {
$count++;
echo $numbering.' ';
$class = ($count % 2 == 0) ? 'white' : '#CCCCCC';
$sum = array_sum($totalcost);
print '<tr style="background-color: '.$class.'">';
print '<td style="vertical-align: top; text-align: left;">'. $numbering .'. '. $item . '</td>';
print '<td style="vertical-align: top; text-align: left;">'.$itemData[$numbering]['projectscostbreakdown_itemdescription'].'</td>';
print '<td style="vertical-align: top; text-align: right;"></td>';
print '<td style="vertical-align: top; text-align: right;"></td>';
print '<td style="vertical-align: top; text-align: right;">'. number_format($sum, 2,'.', ',') . '</td>';
print '<td style="vertical-align: top; text-align: right;"></td>';
print '<td style="vertical-align: top; text-align: left;"></td>';
print '</tr>';
$numbering++;
$totalArea += $sum;
}
print '<tr style="background-color: lightgray; text-align: right;" ><td colspan="6">Section Total: </td><td>'. number_format($totalArea, 2,'.', ',') . '</td></tr>';
$totalSum += $totalArea;
}
print '<tr style="background-color: lightblue; text-align: right;" ><td colspan="6"><b>Grand Total: </b></td><td><b>'. number_format($totalSum, 2,'.', ',') . '</b></td></tr>';
echo '</tbody></table>';
?>
Basically, what I did (which might not be the best option but I couldn't think anything better) was I used $itemData = $query->fetchAll(); after executing $query->execute();. Now if we leave everything the same, table will be empty since pointer is at the last element. Therefore, we must execute again the same query by writing an additional $query->execute(); right after $itemData = $query->fetchAll();.
Now we have basically the same thing as in your example but with one additional variable $itemData with all information about items. To bring out description, quantity, etc. now we can use $itemData[$numbering]['projectscostbreakdown_itemdescription'] where $numbering stands for array's index number.

I keep getting "TCPDF ERROR: Wrong page number on setPage() function:"

I want to print a class bill and i keep getting:
TCPDF ERROR: Wrong page number on setPage() function
Below is my code:
<?php
ob_start();
require_once '../includes/header.php';
require_once '../tcpdf/tcpdf.php';
require_once '../classes/InstitutionDetail.php';
require_once '../classes/ClassMembership.php';
require_once '../classes/Pupil.php';
require_once '../classes/Admission.php';
require_once '../classes/User.php';
require_once '../classes/Photo.php';
require_once '../classes/Bill.php';
require_once '../classes/Payments.php';
confirm_logged_in();
$institutionDetail = new InstitutionDetail();
$classMembership = new ClassMembership();
$pupil = new Pupil();
$admission = new Admission();
$user = new User();
$photo = new Photo();
$bill = new Bill();
$payment = new Payments();
$getUserDetails = $user->getUserByUsername($_SESSION["username"]);
$splitAccessPages = explode("//", $getUserDetails["access_pages"]);
for ($i = 0; $i < count($splitAccessPages); $i++) {
if (!in_array("print_class_bills", $splitAccessPages, TRUE)) {
redirect_to("logout_access.php");
}
}
//$getAcademicTerm = $academicTerm->getActivatedTerm();
//$get_academic_term = $getAcademicTerm["academic_year"] . "/" . $getAcademicTerm["term"];
if (!isset($_SESSION["chosen_term"], $_SESSION["selected_class_name"])) {
// redirect_to("student_bill.php");
$_SESSION["chosen_term"] = "";
$_SESSION["selected_class_name"] = "";
}
$getInstitutionDetail = $institutionDetail->getInstitutionDetails();
$getSchool_name = $getInstitutionDetail["school_name"];
$getSchoolMotor = $getInstitutionDetail["school_motor"];
$getPostalAddress = $getInstitutionDetail["postal_address"];
$getTelephoneNumbers = $getInstitutionDetail["telephone_1"] . " " . $getInstitutionDetail["telephone_2"] . " " . $getInstitutionDetail["telephone_3"];
class MYPDF extends TCPDF {
//Page header
public function Header() {
}
// Page footer
public function Footer() {
// Position at 15 mm from bottom
$this->SetY(-90);
// Set font
$this->SetFont('helvetica', '', 8);
// Page number
// date_default_timezone_set("Africa/Accra");
// $this->Cell(0, 10, date("d/m/Y h:i:sa") . " " . 'Page ' . $this->getAliasNumPage() . '/' . $this->getAliasNbPages(), 0, false, 'R', 0, '', 0, false, 'T', 'M');
$takeNote = "<strong><u>FOOTNOTES:</u></strong>";
$divSaparatefoot = '<div style="width:auto; background-color:mintcream; height:25px; border-bottom:3px solid #ddd;padding-bottom:3px;">'.'</div>';
// $horizontalLine = "<hr style=background:burlywood; height: 5px; />";
$space = "<p></p>";
$msg = "1. When <strong>Total Fees</strong> indicate <strong>credit</strong>, it means that, the school owes the student the said amount.";
$info = "2. All fees must be paid on or before the <strong>re-opening date</strong>.";
$bankNote = "<strong>Bankers:</strong>";
$company = "<strong><em>Software by ANIDROL GHANA:+233 26-764-2898 /+233 24-774-5156</em></strong>";
$institutionDetail = new InstitutionDetail();
$getInstitutionDetail = $institutionDetail->getInstitutionDetails();
$getBank_1 = "1. <strong>" . $getInstitutionDetail["bank_1"] . "</strong> Branch: <strong>" . $getInstitutionDetail["bank_1_branch"] . "</strong> Account Number: <strong>" . $getInstitutionDetail["bank_1_account_number"] . "<strong>";
$getBank_2 = "2. <strong>" . $getInstitutionDetail["bank_2"] . "</strong> Branch: <strong>" . $getInstitutionDetail["bank_2_branch"] . "</strong> Account Number: <strong>" . $getInstitutionDetail["bank_2_account_number"] . "<strong>";
$getBank_3 = "3. <strong>" . $getInstitutionDetail["bank_3"] . "</strong> Branch: <strong>" . $getInstitutionDetail["bank_3_branch"] . "</strong> Account Number: <strong>" . $getInstitutionDetail["bank_3_account_number"] . "<strong>";
$this->writeHTML($divSaparatefoot, true, 0, true, 0);
$this->writeHTML($takeNote, true, 0, true, 0);
$this->writeHTML($space, true, 0, true, 0);
$this->writeHTML($msg, true, 0, true, 0);
$this->writeHTML($info, true, 0, true, 0);
$this->writeHTML($space, true, 0, true, 0);
$this->writeHTML($bankNote, true, 0, true, 0);
$this->writeHTML($getBank_1, true, 0, true, 0);
$this->writeHTML($getBank_2, true, 0, true, 0);
$this->writeHTML($getBank_3, true, 0, true, 0);
$this->writeHTML($company, true, 0, true, 0, 'R');
}
}
$pdf = new MYPDF("", PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
// set header and footer fonts
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
// set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
// set margins
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
// set auto page breaks
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
// set some language-dependent strings (optional)
if (#file_exists(dirname(__FILE__) . "/lang/eng.php")) {
require_once(dirname(__FILE__) . "/lang/eng.php");
$pdf->setLanguageArray($l);
}
// set font
$pdf->SetFont('times', '', 11);
$getClassStudentById = $classMembership->getClassStudentsById($_SESSION["chosen_term"], $_SESSION["selected_class_name"]);
foreach ($getClassStudentById as $value) {
$pdf->startPageGroup();
$pdf->AddPage();
$pdf->setJPEGQuality(75);
$getSingleBillAmount = $bill->getSingleBillingAmount($value["pupil_id"]);
$singleBillAmount = $getSingleBillAmount["billAmount"];
$getTermFees = $bill->getTermFees($value["pupil_id"], $_SESSION["chosen_term"]);
$getPTAAll = $bill->getPTAFeesAll($value["pupil_id"]);
// $termFeesOnly = number_format($getTermFees["termFees"], 2, ".", ",");
$getPTA = $bill->getPTAFees($value["pupil_id"], $_SESSION["chosen_term"]);
$termFees = number_format(($getTermFees["termFees"] + $getPTA["ptaFees"]), 2, ".", ",");
if ($termFees <= 0) {
if ($termFees == 0) {
$termFeesFormated = "";
} else {
$termFeesFormated = "GH¢" . str_replace("-", "", $termFees) . " Credit";
}
} else {
$termFeesFormated = "GH¢" . $termFees;
}
$getFeesPayable = $bill->getStudentAccount($value["pupil_id"]);
$getTotalFeesPaid = $bill->getTotalFeesPaid($value["pupil_id"]);
$getPTAFeesPaid = $bill->getPTAFeesPaid($value["pupil_id"]);
// $getBalance = number_format((($getFeesPayable["allFeesPayable"] + $singleBillAmount + $getPTAAll["ptaFeesAll"]) - ($getTotalFeesPaid["allFeesPaid"])), 2, ".", ",");
$getBalance = number_format((($getFeesPayable["allFeesPayable"] + $singleBillAmount + $getPTAAll["ptaFeesAll"]) - ($getTotalFeesPaid["allFeesPaid"] + $getPTAFeesPaid["ptaFeesPaid"] + $termFees)), 2, ".", ",");
if ($getBalance <= 0) {
if ($getBalance == 0) {
$balanceBroughtForward = "-";
} else {
$balanceBroughtForward = "GH¢" . str_replace("-", "", $getBalance) . " Credit";
}
} else {
$balanceBroughtForward = "GH¢" . $getBalance . " Debit";
}
// $totalFees = number_format(((($getFeesPayable["allFeesPayable"] - $getTotalFeesPaid["allFeesPaid"]) + $singleBillAmount) + $termFees), 2, ".", ",");
$totalFees = number_format((($getFeesPayable["allFeesPayable"] + $singleBillAmount + $getPTAAll["ptaFeesAll"] + $termFees) - ($getTotalFeesPaid["allFeesPaid"] + $getPTAFeesPaid["ptaFeesPaid"] + $termFees)), 2, ".", ",");
if ($totalFees <= 0) {
if ($totalFees == 0) {
$balanceCarriedForward = "-";
} else {
$balanceCarriedForward = "GH¢" . str_replace("-", "", $totalFees) . " Credit";
}
} else {
$balanceCarriedForward = "GH¢" . $totalFees;
}
// table
$getStudentPhoto = $photo->getPhotoById($value["pupil_id"]);
$studentPhoto = "../" . $getStudentPhoto["photo_url"];
$getLogoID = $photo->getSchoolLogoID();
$getSchoolLogo = $photo->getSchoolLogo($getLogoID["logo_id"]);
$schoolLogo = "../" . $getSchoolLogo["photo_url"];
$heading = "<span>GHANA EDUCATION SERVICE</span>"
. "<h1>" . $getSchool_name . "</h1>"
. "<span>" . $getPostalAddress . "</span><br />"
. "<span>" . $getTelephoneNumbers . "</span>";
$pdf->Image($studentPhoto, 155, 60, 35, 35, '', '', '', true, 150, '', false, false, 0, false, false, false);
$pdf->Image($schoolLogo, 5, 7, 34, 37, '', '', '', true, 150, '', false, false, 0, false, false, false);
$tbl_head_heading = '<table cellspacing = "0" cellpadding = "5">';
$tbl_foot_heading = '</table>';
$tbl_heading = '';
$tbl_heading .= '
<tbody>
<tr>
<td style="text-align: center; background-color: #666; color: #fff;" colspan="4">' . $heading . '</td>
</tr>
</tbody>';
$pdf->writeHTML($tbl_head_heading . $tbl_heading . $tbl_foot_heading, true, false, true, false, '');
$className ='<div style="width:auto; background-color:grey;">'.'<b>'. '<strong style="color:#fff; font-size:12px">'. htmlentities(strtoupper($_SESSION["chosen_term"] . " " . "Term Student Bill")) . '</strong>'.'</b>'.'</div>';
$pdf->writeHTML($className, true, 0, true, 0, 'C');
// $horizontalLineII = '<hr style="">'.'</hr>';
$divSaparate = '<div style="width:auto; background-color:mintcream; height:25px; border-bottom:3px solid #ddd;padding-bottom:3px;">'.'</div>';
$pdf->writeHTML($divSaparate);
//$pdf->writeHTML($horizontalLineII);
$headingSpace = "<div></div>";
$pdf->writeHTML($headingSpace, true, 0, true, 0);
//$horizontalLine = "<hr style='background-color:burlywood; height: 5px;'>"."</hr>";
$divSaparateLine = '<div style="width:auto; background-color:mintcream; height:25px; border-bottom:3px solid #ddd;padding-bottom:3px;">'.'</div>';
$getStudentData = $pupil->getPupilById($value["pupil_id"]);
$getStudentName = $getStudentData["other_names"] . " " . $getStudentData["family_name"];
$getStudentID = $getStudentData["pupil_id"];
$getGender = $getStudentData["sex"];
$getBoardingStatus = $value["boarding_status"];
$getClassName = $value["class_name"];
$tbl_head_title = '<table cellspacing = "10" cellpadding = "0" border = "0">';
$tbl_foot_title = '</table>';
$tbl_title = '';
$tbl_title .= '
<tbody>
<tr style="color: #000;">
<td style="text-align: right; width: 20%;"><strong>Name:</strong></td>
<td style="text-align: left; font-weight:bold;margin:5px; border-bottom:1.5px solid #ddd;padding-bottom:3px;">' . $getStudentName . '</td>
</tr>
<tr style="color: #000;">
<td style="text-align: right; width: 20%;"><strong>ID Number:</strong></td>
<td style="text-align: left; border-bottom:1.5px solid #ddd;padding-bottom:3px; width:100px;">' . $getStudentID . '</td>
</tr>
<tr style="color: #000;">
<td style="text-align: right; width: 20%; "><strong>Gender:</strong></td>
<td style="text-align: left; border-bottom:1.5px solid #ddd;padding-bottom:3px; width:100px;">' . $getGender . '</td>
</tr>
<tr style="color: #000;">
<td style="text-align: right; width: 20%;"><strong>Status:</strong></td>
<td style="text-align: left; border-bottom:1.5px solid #ddd;padding-bottom:3px; width:100px;">' . $getBoardingStatus . '</td>
</tr>
<tr style="color: #000;">
<td style="text-align: right; width: 20%;"><strong>Class:</strong></td>
<td style="text-align: left; font-weight:bold; border-bottom:1.5px solid #ddd;padding-bottom:3px; width:100px;">' . $getClassName . '</td>
</tr>
<tr style="color: #000;">
<td style="text-align: right; width: 20%;"><strong>Balance b/f:</strong></td>
<td style="text-align: left;">' . $balanceBroughtForward . '</td>
</tr>
<tr style="color: #000;">
<td style="text-align: right; width: 20%;"><strong>Term Fees:</strong></td>
<td style="text-align: left;">' . $termFeesFormated . '</td>
</tr>
<tr style="color: #000;">
<td style="text-align: right; width: 20%;"><strong>Total Fees:</strong></td>
<td style="text-align: left;">' . $balanceCarriedForward . '</td>
</tr>
</tbody>';
$pdf->writeHTML($tbl_head_title . $tbl_title . $tbl_foot_title, FALSE, false, true, false, '');
$pdf->writeHTML($divSaparateLine, true, 0, true, 0);
// list of bill items
$tbl_head_description = '<table cellspacing = "2" cellpadding = "5" border = "0">';
$tbl_foot_description = '</table>';
$tbl_description = '';
$tbl_description .= '
<tbody>
<tr style="color: #000;">
<td style="width: 8.5%;"> </td>
<td style="width: 67%; text-align: left;">' . "<strong>BILL ITEMS</strong>" . '</td>
<td style="text-align: right; width: 16%;">' . "<strong>GH¢</strong>" . '</td>
</tr>
</tbody>';
$pdf->writeHTML($tbl_head_description . $tbl_description . $tbl_foot_description, FALSE, false, true, false, '');
$classBillItemsForStudent = $bill->getClassBillForStudent($value["class_name"], $_SESSION["chosen_term"]);
foreach ($classBillItemsForStudent as $classBillItemStudent) {
if ($getBoardingStatus === "Day Student") {
$schoolFees = $classBillItemStudent["day_amount"];
} else {
$schoolFees = $classBillItemStudent["boarding_amount"];
}
$tbl_head_item = '<table cellspacing = "1" cellpadding = "0" border = "0">';
$tbl_foot_item = '</table>';
$tbl_item = '';
$tbl_item .= '
<tbody>
<tr style="color: #000;">
<td style="width: 10%;"> </td>
<td style="width: 70%;">' . $classBillItemStudent["bill_item"] . '</td>
<td style="text-align: right; width: 10%;">' . number_format($schoolFees, 2, ".", ",") . '</td>
</tr>
</tbody>';
$pdf->writeHTML($tbl_head_item . $tbl_item . $tbl_foot_item, FALSE, false, true, false, '');
}
if ($getGender === "Male") {
$classBillItemsForMale = $bill->getClassBillForMale($value["class_name"], $_SESSION["chosen_term"]);
foreach ($classBillItemsForMale as $classBillItemMale) {
if ($getBoardingStatus === "Day Student") {
$schoolFeesMale = $classBillItemMale["day_amount"];
} else {
$schoolFeesMale = $classBillItemMale["boarding_amount"];
}
$tbl_head_item = '<table cellspacing = "1" cellpadding = "0" border = "0">';
$tbl_foot_item = '</table>';
$tbl_item = '';
$tbl_item .= '
<tbody>
<tr style="color: #000;">
<td style="width: 10%;"> </td>
<td style="width: 70%;">' . $classBillItemMale["bill_item"] . '</td>
<td style="text-align: right; width: 10%;">' . number_format($schoolFeesMale, 2, ".", ",") . '</td>
</tr>
</tbody>';
$pdf->writeHTML($tbl_head_item . $tbl_item . $tbl_foot_item, FALSE, false, true, false, '');
}
} else {
$classBillItemsForFemale = $bill->getClassBillForFemale($value["class_name"], $_SESSION["chosen_term"]);
foreach ($classBillItemsForFemale as $classBillItemFemale) {
if ($getBoardingStatus === "Day Student") {
$schoolFeesFemale = $classBillItemFemale["day_amount"];
} else {
$schoolFeesFemale = $classBillItemFemale["boarding_amount"];
}
$tbl_head_item = '<table cellspacing = "1" cellpadding = "0" border = "0">';
$tbl_foot_item = '</table>';
$tbl_item = '';
$tbl_item .= '
<tbody>
<tr style="color: #000;">
<td style="width: 10%;"> </td>
<td style="width: 70%;">' . $classBillItemFemale["bill_item"] . '</td>
<td style="text-align: right; width: 10%;">' . number_format($schoolFeesFemale, 2, ".", ",") . '</td>
</tr>
</tbody>';
$pdf->writeHTML($tbl_head_item . $tbl_item . $tbl_foot_item, FALSE, false, true, false, '');
//$get_term_from_session = $_SESSION["chosen_term"];
//$get_session_class = $_SESSION["selected_class_name"];
// $get_class_memebership = $classMembership ->getClassMembersByClassName($_SESSION["selected_class_name"]);
//
// if( $get_class_memebership){
//
// }
$getTotalBillForClass = $bill ->getTotalStudentCharges( $_SESSION["selected_class_name"],$_SESSION["chosen_term"]);
$tbl_head_itema = '<table cellspacing = "1" cellpadding = "0" border = "0">';
$tbl_foot_itema = '</table>';
$tbl_itema = '';
$tbl_itema.= '
<tbody>
<tr style="color: #000;">
<td style="width: 10%;"> </td>
<td style="width: 70%;">' . 'TOTAL:' . '</td>
<td style="text-align: right; width: 10%;">' . number_format($getTotalBillForClass, 2, ".", ",") . '</td>
</tr>
</tbody>';
$pdf->writeHTML($tbl_head_itema . $tbl_itema . $tbl_foot_itema, FALSE, false, true, false, '');
}
}
}
$pdf->lastPage();
ob_end_clean();
$pdf->Output();
Any time i try to generate a bill i keep getting that error and i dont know where i am wrong too...Can any body please help...

Double if with database query

I have this code
while ($row = mysql_fetch_assoc($wynik)) {
echo '<tr class="ad"> ';
foreach ($row as $key => $value) {
if ($value != null){
if ($value<=1){
$wymiar = $key."x".$first;
$wynik3 = mysql_query("SELECT * FROM `".$nazwa2."` where `tak` = '".$wymiar."' ");
while ($row = mysql_fetch_array($wynik3)) {
if ($row["tak"] == $wymiar){
echo $row["id"];
echo '<td width=25px; style="background-color: red; border-color: blue;" border="1"><p style="display:block;">'.$key.'x'.$first.'</p></td>';
}
unset($wymiar);
}
echo '<td width=25px; style="background-color: green; border-color: blue;" border="1"><p style="display:block;">'.$key.'x'.$first.'</p></td>';
} else {
echo '<td width=25px; style="background-color: yellow; border-color: blue;" border="1">'.$value."</td>";
$first = $value;
}
} else {
echo '<td width=25px; style="background-color: magenta; border-color: blue;" border="1">'.$value."</td>";
}
} echo "</tr>";
}
How to correctly use "if ... else" statement, Now is something wrong. It adds a red cell but also leaves a record with the green cell and moves the entire row
Try this. It only queries for 1 row in the $wynik3 query, by using LIMIT 1. Then it tests whether that query was successful; if it was, it displays a red cell, otherwise it displays a green cell.
while ($row = mysql_fetch_assoc($wynik)) {
echo '<tr class="ad"> ';
foreach ($row as $key => $value) {
if ($value != null){
if ($value<=1){
$wymiar = $key."x".$first;
$wynik3 = mysql_query("SELECT * FROM `".$nazwa2."` where `tak` = '".$wymiar."' LIMIT 1");
if ($row = mysql_fetch_array($wynik3)) {
echo $row["id"];
echo '<td width=25px; style="background-color: red; border-color: blue;" border="1"><p style="display:block;">'.$key.'x'.$first.'</p></td>';
} else {
echo '<td width=25px; style="background-color: green; border-color: blue;" border="1"><p style="display:block;">'.$key.'x'.$first.'</p></td>';
}
} else {
echo '<td width=25px; style="background-color: yellow; border-color: blue;" border="1">'.$value."</td>";
$first = $value;
}
} else {
echo '<td width=25px; style="background-color: magenta; border-color: blue;" border="1">'.$value."</td>";
}
} echo "</tr>";
}
BTW, it's echoing $row["id"] outside the <td>, which isn't valid HTML. I'm assuming that's just there for debugging, not part of the production table.
Try this
while ($row = mysql_fetch_assoc($wynik)) {
echo '<tr class="ad"> ';
foreach ($row as $key => $value) {
if (!empty($value)){
if ($value<=1){
$wymiar = $key."x".$first;
$wynik3 = mysql_query("SELECT * FROM `".$nazwa2."` where `tak` = '".$wymiar."' ");
if(mysql_num_rows($wynik3)== 0){
echo '<td width=25px; style="background-color: green; border-color: blue;" border="1"><p style="display:block;">'.$key.'x'.$first.'</p></td>';
} else {
while ($row = mysql_fetch_array($wynik3)) {
if ($row["tak"] == $wymiar){
echo $row["id"];
echo '<td width=25px; style="background-color: red; border-color: blue;" border="1"><p style="display:block;">'.$key.'x'.$first.'</p></td>';
}
unset($wymiar);
}
}
} else {
echo '<td width=25px; style="background-color: yellow; border-color: blue;" border="1">'.$value."</td>";
$first = $value;
}
} else {
echo '<td width=25px; style="background-color: magenta; border-color: blue;" border="1">'.$value."</td>";
}
} echo "</tr>";
}
Try this,
while ($row = mysql_fetch_assoc($wynik))
{
foreach ($row as $key => $value)
{
$arrTableTD = array();
if ($value != null)
{
if ($value<=1)
{
$wymiar = $key."x".$first;
$wynik3 = mysql_query("SELECT * FROM `".$nazwa2."` where `tak` = '".$wymiar."' ");
while ($row = mysql_fetch_array($wynik3))
{
if ($row["tak"] == $wymiar)
{
$arrTableTD[] = $row["id"];
$arrTableTD[] = '<td width=25px; style="background-color: red; border-color: blue;" border="1"><p style="display:block;">'.$key.'x'.$first.'</p></td>';
}
unset($wymiar);
}
$arrTableTD[] = '<td width=25px; style="background-color: green; border-color: blue;" border="1"><p style="display:block;">'.$key.'x'.$first.'</p></td>';
} else {
$arrTableTD[] = '<td width=25px; style="background-color: yellow; border-color: blue;" border="1">'.$value."</td>";
$first = $value;
}
} else {
$arrTableTD[]= '<td width=25px; style="background-color: magenta; border-color: blue;" border="1">'.$value."</td>";
}
}
echo $tablerow = '<tr class="ad">'.implode("",$arrTableTD).'</tr>';
}
You might have an issue because you're using the variable $row two times in you code.
Here
foreach ($row as $key => $value)
And here
while ($row = mysql_fetch_array($wynik3))
The second use of it create a problem true renaming it.
I don't know if it will solve your problem, but is it definitely a first correction to make

PHP - seperate array based on characters in key

I have a PHP array from a submitted form that looks like the following
$form_data = Array (
[input_1_1] => Product Name
[input_1_2] => $8.00
[input_1_3] => 2
[input_2_1] => Other Product Name
[input_2_2] => $3.50
[input_2_3] => 8
)
I am looking for the best way to parse this so I can build something markup like this:
<table>
<tr>
<td>Product Name</td>
<td>$8.00</td>
<td>2</td>
</tr>
<tr>
<td>Other Product Name</td>
<td>$3.50</td>
<td>8</td>
</tr>
</table>
What would be most kosher way to do this?
Should I split this array into smaller arrays based on the 1st number (and then loop them)?
Alternatively should I just build the markup based on sets of three, like:
<table>
<tr>
<td><?php echo $form_data[1]; ?></td>
<td><?php echo $form_data[2]; ?></td>
<td><?php echo $form_data[3]; ?></td>
</tr>
<tr>
<td><?php echo $form_data[4]; ?></td>
<td><?php echo $form_data[5]; ?></td>
<td><?php echo $form_data[6]; ?></td>
</tr>
</table>
Any help/advice appreciated.
take a look on this example: http://codepad.org/zhKbc4p1
$arr = array('input_1_1'=>'Name', 'input_1_2'=>'$8', 'input_1_3'=>1, 'input_2_1'=>'Name', 'input_2_2'=>'$28', 'input_2_3'=>1);
$chunk = array_chunk($arr, 3);
print_r($chunk);
foreach( $chunk as $val ){
foreach($val as $v){
echo $v . "\r\n";
}
echo "\r\n\r\n";
}
Expected HTML format:
foreach( $chunk as $val ){
echo "<tr>";
foreach($val as $v){
echo "<td>" . $v . "</td>";
}
echo "</tr>";
}
$last_group = '';
foreach ($form_data as $key => $value) {
preg_match('/input_(\d+)/', $key, $match);
if ($match[1] != $last_group) {
if ($last_group) {
echo "</tr>\n";
}
echo "<tr>\n";
$last_group = $match[1];
}
echo "<td>$value</td>\n";
}
if ($last_group) {
echo "</tr>\n";
}
It would be better to structure your form like this, though:
<input type="text" name="name[]">
<input type="text" name="price[]">
<input type="text" name="quantity[]">
Then the $_POST['name'], $_POST['price'] and $_POST['quantity'] will be arrays, and you can iterate over them:
foreach ($_POST['name'] AS $i => $name) {
$price = $_POST['price'][$i];
$quantity = $_POST['quantity'][$i];
// Output the table row
}
Assuming each table row has 3 elements each;
<?php
echo "<table>
<tr>";
$form_data = Array (
"input_1_1" => "Product Name",
"input_1_2" => "$8.00",
"input_1_3" => "2",
"input_2_1" => "Other Product Name",
"input_2_2" => "$3.50",
"input_2_3" => "8"
);
$intRowBefore = 1;
foreach( $form_data as $strKey => $strVal ) {
$intRow = explode("_", $strKey)[1];
if( $intRowBefore != $intRow ) {
echo "</tr><tr>";
$intRowBefore = $intRow;
}
echo "<td>". $strVal ."</td>";
}
echo "</tr></table>";
Consider
<?php
$form_data = array();
$form_data['input_1_1'] = 'Product Name';
$form_data['input_1_2'] = '$8.00';
$form_data['input_1_3'] = '2';
$form_data['input_2_1'] = 'Other Product Name';
$form_data['input_2_2'] = '$3.50';
$form_data['input_2_3'] = '8';
// Get unique keys
function get_unique_keys($keys)
{
$arr = array();
foreach($keys as $k=>$v){
$arr[] = substr($k, 0, strlen($k)-2);
}
return array_unique($arr);
}
$keys = get_unique_keys($form_data);
// Output
printf("<table>\n");
foreach($keys as $k)
{
printf(" <tr>\n");
printf(" <td>%s</td>\n", $form_data[$k.'_1']);
printf(" <td>%s</td>\n", $form_data[$k.'_2']);
printf(" <td>%s</td>\n", $form_data[$k.'_2']);
printf(" </td>\n");
}
printf("</table>\n");
Which outputs:
<table>
<tr>
<td>Product Name</td>
<td>$8.00</td>
<td>$8.00</td>
</td>
<tr>
<td>Other Product Name</td>
<td>$3.50</td>
<td>$3.50</td>
</td>
</table>
See it in action: http://ideone.com/355STr
It's not super complicated. It gets the key "roots" we'll call them (input_1, input_2, etc) and loops over those, appending the additional _1,_2,_3 when needed.
A better solution long-term would be to redesign the form, but that's not always a possibility.
Try This
$form_data = Array (
'[input_1_1]' => 'Product Name',
'[input_1_2]' => '$8.00',
'[input_1_3]' => '2',
'[input_2_1]' => 'Other Product Name',
'[input_2_2]' => '$3.50',
'[input_2_3]' => '8'
);
echo "<table>";
foreach($form_data as $k=>$v)
{
echo "<tr>";
echo "<td>".$v."&lt/td>";
echo "</tr>";
}
echo "</table>";
<?php
$form_data = array(
'input_1_1' => 'Product Name',
'input_1_2' => 8.00,
'input_1_3' => 2,
'input_2_1' => 'Other Product Name',
'input_2_2' => 3.50,
'input_2_3' => 8
);
end($form_data);
$counter = explode('_',key($form_data));
?>
<table>
<?php
$i = 1;
$j = 1;
for ($k = 1; $k <= $counter[1]; $k++) {
?>
<tr>
<td><?php echo $form_data['input_' . $j . '_' . $i]; ?></td>
<td><?php $i++;echo $form_data['input_' . $j . '_' . $i]; ?></td>
<td><?php $i++;echo $form_data['input_' . $j . '_' . $i]; ?></td>
</tr>
<?php
if ($i == 3) {
$i = 1;
$j++;
}
}
?>
</table>

Categories