How to make a table in phpword? - php

Bellow are my code, i get four column from these, but the result shows every one data will loop in four time in one column then it appear again in new column with the same data.
<?php
$tampil_data = $this->in_elektronik_model->tampil_data(); //load data
foreach ($tampil_data as $tampildata) {
for ($i = 0; $i < 4; $i++) {
$table->addRow(500); //make new row
for ($j = 0; $j < 4; $j++) {
$table->addCell(2000)->addText(htmlspecialchars($tampildata->elektronik_nama)); //content of table
}
}
}
model
function tampil_data() {
$this->db->where('elektronik_status_aktif', 0);
$tampil = $this->db->get('in_elektronik');
if ($tampil->num_rows() > 0) {
return $tampil->result();
} else {
return array();
}
}
How to make table with four column, where the content of table will appear from right column to left and appear just one data in one time, after four column are full, it makes new row?

You can refer this code. This is the way i have done table in view page
<table border="1">
<tr role="row">
<th width="5%">Featured Id</th>
</tr>
<?php
if(!empty($results))
{
foreach ($results as $row) {
?><tr>
<td class=" "><?php echo $row->fet_id; ?></td>
</tr>
<?php }}
?>
</table>

Related

Unable to get database results using whereMonth query inside a for loop php laravel

I want to query a database by making use of a whereMonth clause in laravel using a for loop but I am getting an empty array. If I replace $m in whereMonth clause with an integer like 7 it pulls the data.
<table class="table table-bordered table-hover expenses-report" id="expenses-report-table">
<thead>
<tr>
<th class="bold">Category</th>
<?php
for ($m=1; $m<=12; $m++) {
echo ' <th class="bold">' .date('F', mktime(0,0,0,$m,1)) . '</th>';}
?>
<th class="bold">year ({{\Carbon\Carbon::now()->format('Y')}})</th>
<?php
?>
</tr>
</thead>
<tbody>
#foreach ($categories as $category)
<tr>
<td>
{{$category->name}}
<?php
for ($m = 1; $m <= 12; $m++) {
if (!isset($netMonthlyTotal[$m])) {
$netMonthlyTotal[$m] = array();
}
$expense_results = $expenses->whereMonth('date',$m)
->whereYear('date', \Carbon\Carbon::now()->format('Y'))
->where('category', $category->id)
->get();
print_r($expense_results);
$total_expenses = array();
echo '<td>';
foreach ($expense_results as $expense) {
$expense = $expenses->where('id', $expense->id)->first();
$total = $expense->amount;
$totalTaxByExpense = 0;
// Check if tax is applied
if ($expense->tax != 0) {
$totalTaxByExpense+= ($total / 100 * $expense->tax);
}
$taxTotal[$m][] = $totalTaxByExpense;
$total_expenses[] = $total;
}
$total_expenses = array_sum($total_expenses);
// Add to total monthy expenses
array_push($netMonthlyTotal[$m], $total_expenses);
if (!isset($totalNetByExpenseCategory[$category->id])) {
$totalNetByExpenseCategory[$category->id] = array();
}
array_push($totalNetByExpenseCategory[$category->id], $total_expenses);
// Output the total for this category
if (count($categories) <= 8) {
echo $total_expenses;
} else {
// show tooltip for the month if more the 8 categories found. becuase when listing down you wont be able to see the month
echo '<span data-toggle="tooltip"
title="' . date('F', mktime(0, 0, 0, $m, 1)) . '">' . $total_expenses . '</span>';
}
echo '</td>';
}
?>
</td>
<td class="bg-odd">
{{array_sum($totalNetByExpenseCategory[$category->id])}}
</td>
</tr>
#endforeach
</tbody>
</table>
I basically want to return results matching the search query including the whereMonth
Can you replace this part
$query->whereMonth('date', $m);
with this
$query->whereMonth('date', (string) $m);
And then try again. I guess its not accepting integers.
I was able to get it to work by making use of Raw query
$rawQuery ="SELECT amount, id,tax FROM tblexpenses WHERE MONTH(date) = $m AND YEAR(CURRENT_DATE) AND category=$category->id GROUP BY id";
$expense_results = DB::select(DB::raw($rawQuery));
Though I would appreciate it if someone can help to translate this query to laravel

PHP Looping array data in a table format & an errant value

I have the following code. How can I get my results ($x) for the foreach function to print into the table at the top, but in columns instead of a straight horizontal row? Is there a way to do this without just inserting each individual value into the HTML table? I need to do the same for my $employee['name'] variable but am not sure how I could get these values inserted into a table format without going one by one and entering the value myself.
Also, one value for $x at the end stays an integer and does not echo the string variable specified by the foreach function, is there a way I could fix this?
<!--4.3-->
<table>
<tr>
<td>Employee name</td><td></td><td></td><td></td><td></td><td></td>
<td>Type of Paying</td><td></td><td></td><td></td><td></td><td></td>
</tr>
<tr>
<td></td><td></td><td></td><td></td><td></td><td></td>
<td><?php echo $x;?></td><td></td><td></td><td></td><td></td><td></td>
</tr>
</table>
</html>
<?php
foreach ($employees as $employee) {
$x = ($employee['wage'] * $employee['hrs']) * 4;
if ( 3000 <= $x ) {
echo "High paying";
} elseif (2000 <= $x && $x <= 2999) {
echo "Good paying";
} else {
echo "Low paying";
}
}
print_r ($x);
I inserted the foreach function into the table where I needed the results printed, then added tags within the ifelse statement after each parameter, and it worked like a charm.
My code for that table now looks like this:
<html>
<table>
<tr>
<td>Employee name</td><td></td><td></td><td></td><td></td><td></td>
<td>Type of Paying</td><td></td><td></td><td></td><td></td><td></td>
</tr>
<tr>
<td></td><td></td><td></td><td></td><td></td><td></td>
<td> <?php
foreach ($employees as $employee) {
$x = ($employee['wage'] * $employee['hrs']) * 4;
if ( 3000 <= $x ) {
echo "High paying"; echo "<br/>";
} elseif (2000 <= $x && $x <= 2999) {
echo "Good paying"; echo "<br/>";
} else {
echo "Low paying"; echo "<br/>";
}
} echo "<br/>" ; ?>
</td><td></td><td></td><td></td><td></td><td></td>
</tr>
</table>
The other section above the foreach function will hold employee names and is not yet filled out to match.

SUM of columns in a table (JSON data) in PHP

Couldn't find a specific answer to this so thought I'd ask. In short, I have a table that retrieves information from an API, based on data stored in my database and all I want to do is to get a total of certain, not all, columns from that table so that I can use them elsewhere on the site. As an example, let's use the Profit/Loss column and Total Divi. Do I have to somehow store the results as an array so that I can retrieve it elsewhere or is it something different?
<th>Profit/Loss</th>
<?php
for($x=0;$x<$y;$x++)
{?>
<tr>
<td class="input"><?php
if($pri[$x] > $lastprice[$x])
{
echo ($lastprice[$x]-$pri[$x]) * $vol[$x];
}
else if($pri[$x] < $lastprice[$x])
{
echo ($lastprice[$x]-$pri[$x]) * $vol[$x];
}
else
echo '0';
?></td>
<td><?php
$div = file_get_contents("https://api.iextrading.com/1.0/stock/market/batch?symbols=$symbol[$x]&types=stats&filter=dividendRate");
$div = json_decode($div,TRUE);
foreach($div as $divi => $value) {
echo $value['stats']['dividendRate'];
}
?></td>
<td><?php
$firstno = floatval($vol[$x]);
$secondno = floatval($value['stats']['dividendRate']);
$sum = $firstno * $secondno;
print ($sum);
?></td>
</tr>
<?php } ?>
So I only left the profit/loss row/column as well as dividend amount (2nd column) and dividend total, just so you can see how I get these numbers in the first place.
Your requirement is, you want to use the profit/loss and total dividend column data of each row at the later stage of your code. What you can do is, create an empty array before the outermost for loop, and in each iteration of the loop, append the pair where key would be $x and value would be an array of profit/loss and total dividend column data.
<th>Profit/Loss</th>
<?php
$arr = array();
for($x=0; $x < $y; $x++){
?>
<tr>
<td class="input">
<?php
$profitOrLoss = ($lastprice[$x]-$pri[$x]) * $vol[$x];
echo $profitOrLoss;
?>
</td>
<td>
<?php
$div = file_get_contents("https://api.iextrading.com/1.0/stock/market/batch?symbols=$symbol[$x]&types=stats&filter=dividendRate");
$div = json_decode($div,TRUE);
$sum = 0;
foreach($div as $divi => $value) {
echo $value['stats']['dividendRate'];
$sum += (floatval($vol[$x]) + floatval($value['stats']['dividendRate']));
}
?>
</td>
<td>
<?php
echo $sum;
?>
</td>
</tr>
<?php
$arr[$x] = array('profitOrLoss' => $profitOrLoss, 'sum' => $sum);
}
?>
Update(1):
Based on your comment, all I want is to add up all the rows in Profit/Loss column together as well as rows in Total Divi column together. the solution code would be like this:
<th>Profit/Loss</th>
<?php
$profitOrLossSum = 0;
$dividendRateSum = 0;
for($x=0; $x < $y; $x++){
?>
<tr>
<td class="input">
<?php
$profitOrLoss = ($lastprice[$x]-$pri[$x]) * $vol[$x];
$profitOrLossSum += $profitOrLoss;
echo $profitOrLoss;
?>
</td>
<td>
<?php
$div = file_get_contents("https://api.iextrading.com/1.0/stock/market/batch?symbols=$symbol[$x]&types=stats&filter=dividendRate");
$div = json_decode($div,TRUE);
$sum = 0;
foreach($div as $divi => $value) {
echo $value['stats']['dividendRate'];
$sum += (floatval($vol[$x]) + floatval($value['stats']['dividendRate']));
$dividendRateSum += floatval($value['stats']['dividendRate']);
}
?>
</td>
<td>
<?php
echo $sum;
?>
</td>
</tr>
<?php
}
$arr = array('profitOrLossSum' => $profitOrLossSum, 'dividendRateSum' => $dividendRateSum);
?>
Sidenote: If you want to see the complete array structure, do var_dump($arr);

php sidebar and footer inside main

I help develop my school's website what I can not figure out is why on a certain page the sidebar and footer go into the table main. It only does this for two thing custodial and kitchen even when I think the code for say administrators is the same code and looks the same to me.
This is the code used to generate the teachers page
The link below will take you to the broken page since I can't post pictures
http://gwhs.kana.k12.wv.us/academics/display.php?action=teacher&id=103
While the link below will take you to one that actually works
http://gwhs.kana.k12.wv.us/academics/display.php?action=teacher&id=24
If you want the entire file for this code let me know and I will post a link
function dTeacher() {
global $db, $id;
if ($stmt = $db->prepare("SELECT name, department, schedule, education, whyteach, phone, email, image, quote FROM teachers WHERE id = ?"))
{
$stmt->bind_param('i', $id);
$stmt->execute();
$res = $stmt->get_result();
$row = $res->fetch_assoc();
$stmt->close();
$schedule = array();
$schedule = explode(",",$row['schedule']);
$education = explode(",",$row['education']);
$noshow = array(20, 14, 25, 15, 24, 21, 23);
print '<h1>Viewing '.$row['name'].'\'s Profile!</h1>';
if ($row['image']) {
print '<img style="max-width:40%; display: block; margin: 2% auto;" src="'.$row['image'].'" alt="Teacher Image Here">';
}
if (!(in_array($row['department'], $noshow))) {
print '<h3>Schedule</h3>
<table id="maindata">
<tr id="head"><td style="width:30%;">Period</td><td style="width:70%;">Class</td></tr>';
for ($i=0; $i<count($schedule); $i++)
{
$oddeven = ($i%2==0) ? "even" : "odd";
$scnum = $schedule[$i];
$scresult = $db->query("SELECT id, name FROM classes where id = {$scnum} LIMIT 1");
$scrow = $scresult->fetch_assoc();
if ($scnum == 1337) {
$scrow['name'] = "OFF";
} //off periods
print '<tr id="'.$oddeven.'"><td style="width:30%;">'.$i.'</td><td style="width:70%;">'.$scrow['name'].'</td></tr>';
}
}
if ($row['education']) {
print "</table><h3>Education</h3>";
for ($i=0; $i<count($education); $i++)
{
$oddeven = ($i%2==0) ? "even" : "odd";
print '<table id="maindata"><tr id="'.$oddeven.'"><td>'.$education[$i].'</td></tr>';
}
print '</table>';
}
if ($row['phone'] || $row['email']) {
print '
<h3>Contact</h3>
<table id="maindata"><tr id="even"><td style="width:30%;">Phone</td><td>'.$row['phone'].'</td></tr>
<tr id="odd"><td style="width:30%;">Email</td><td>'.$row['email'].'</td></tr></table>';
}
if ($row['whyteach'] != "") {
print '<h3>Why do you teach?</h3>
<table id="maindata"><tr id="even"><td><p>'.$row['whyteach'].'</p></td></tr></table>';
}
if ($row['quote'] != "") {
print '<h3>Favorite Quote</h3>
<table id="maindata"><tr id="even"><td><p>'.$row['quote'].'</p></td></tr></table>';
}
}
else {
print "Error with your request.";
die();
}
}
You have a bug here, you are not closing table tag:
if (!(in_array($row['department'], $noshow))) {
print '<h3>Schedule</h3>
<table id="maindata">
<tr id="head"><td style="width:30%;">Period</td><td style="width:70%;">Class</td></tr>';
for ($i=0; $i<count($schedule); $i++)
{
$oddeven = ($i%2==0) ? "even" : "odd";
$scnum = $schedule[$i];
$scresult = $db->query("SELECT id, name FROM classes where id = {$scnum} LIMIT 1");
$scrow = $scresult->fetch_assoc();
if ($scnum == 1337) {
$scrow['name'] = "OFF";
} //off periods
print '<tr id="'.$oddeven.'"><td style="width:30%;">'.$i.'</td><td style="width:70%;">'.$scrow['name'].'</td></tr>';
}
echo "</table>";
}
Because of this, when the profile has Schedule the table is not closed and the page will display bad.
And closes it here:
if ($row['education']) {
print "<h3>Education</h3>";
With two modifications the web should do its work fine.
Take a look this HTML validator, it will help you:
http://validator.w3.org/check?uri=http%3A%2F%2Fgwhs.kana.k12.wv.us%2Facademics%2Fdisplay.php%3Faction%3Dteacher%26id%3D103&charset=%28detect+automatically%29&doctype=Inline&group=0
Best regards.
First words: You should re-think the layout. Creating multiple tables to display page content is not the best approach and furthermore IDs have to be unique. So for valid HTML you can't have multiple tables with the ID maindata.
As mentioned by cmorrissey in the comments, you're not closing the first table, unless you enter the next if statement. Furthermore this part
if ($row['education']) {
print "</table><h3>Education</h3>";
for ($i=0; $i<count($education); $i++) {
$oddeven = ($i%2==0) ? "even" : "odd";
print '<table id="maindata"><tr id="'.$oddeven.'"><td>'.$education[$i].'</td></tr>';
}
print '</table>';
}
of your code closes the previous <table id="maindata"> but opens a new one in each iteration of the loop. After the loop, your closing just one of them. So if it is correct, that you want to create multiple of these tables, you should close them in the loop as well:
for ($i=0; $i<count($education); $i++) {
$oddeven = ($i%2==0) ? "even" : "odd";
print '<table id="maindata"><tr id="'.$oddeven.'"><td>'.$education[$i].'</td></tr>';
print '</table>';
}

Hide column if column is empty i.e. array element is empty

I have an array such:
$prices = array();
Along with a MySQL query and fetch:
$query = "SELECT $columns FROM Prices WHERE `key` LIKE '$rows' LIKE '$AirportPU' AND rate LIKE '$rate'";
if($results = $db->query($query))
{
if($results->num_rows)
{
while($row = $results->fetch_object())
{
$prices[] = $row;
}
$results->free();
}
I've printed out the table using the following code: (I have removed some table columns)
<?php
if(!count($prices)) {
echo '<p>No results found for your current search. Use the inputs to the left to change the filters.</p>';
} else {
?>
<table>
<thead>
<tr>
<th>Location</th>
<th>City</th>
</tr>
</thead>
<tbody>
<?php
foreach ($prices as $p) {
?>
<tr>
<td> <?php echo $p->Location; ?> </td>
<td> £<?php echo $p->City; ?> </td>
</tr>
<?php
}
?>
</tbody>
</table>
<?php } ?>
I can return data from the MySQL query, and print this to the table. However, sometimes not all the columns need be printed as they have no values. I would like to hide these columns.
I have tried checking the array using:
print (isset($prices["City"])) ? "Exists</br>" : "Doesn't Exist</br>" ;
But that always returns "Doesn't Exist"
if (array_key_exists("City",$prices))
{
echo "Element exists!";
}
else
{
echo "Element does not exist!";
}
That also returns false.
You need to check it inside the foreach loop which you are executing.
print (isset($p->City)) ? "Exists</br>" : "Doesn't Exist</br>" ;
Check with
if(empty($price['City'] || $price['City'] == "")){
//Hide column
}

Categories