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.
Related
I want to display checked checkbox which are stored as values in a mysql database.
For now the table stores the value of the checkbox being checked in the database. The header and first column are fetched from three different tables in the database. While the values of the checked check-boxes gets saved in a same table.
Here's the code for inserting the data.
$active = "CourseReport";
require_once 'pages/header.php';
require_once './functions/schema-functions.php';
require_once './functions/report-functions.php';
$course = Schema::getCourseReport();
$objective = Schema::getObjective();
$goals = Schema::getGoals();
$mainobj = Schema::getMainObjectives();
$subobj = Schema::getSubObjectives();
?>
<form id="addReport" action ='./functions/report-functions.php' method="post">
<table id="table1" class="table table-hover">
<thead>
<?php
echo '<tr><th>Goals</th>';
for ($i = 0; $i < count($course); $i++) {
echo '<th id = "rotate1">'. $course[$i]->commonName . '</th>';
}
echo '</tr>';
?>
</thead>
<tbody>
<?php
for ($y = 0; $y < count($goals); $y++) {
echo '<tr class="clickable"><th class="toggle">Goal#'.$goals[$y]['GoalId'].':'." " .' '.$goals[$y]['Goals'].'</th>
</tr>';
?>
<?php
for( $z = 0; $z < count($mainobj); $z++){
if($mainobj[$z]['GoalId'] == $goals[$y]['GoalId']) {
echo '<tr class="expander"><th class=row-header>Objective#'.$mainobj[$z]['MainObjId'].':'." ".' '.$mainobj[$z]['MainObjectives'].'</th>
</tr>';
?>
<?php
for ($j = 0; $j< count($subobj); $j++) {
if($mainobj[$z]['MainObjId'] == $subobj[$j]['MainObjId']){
echo '<tr class="expander"><td class=row-header>'.$subobj[$j]['SubObjId'].' ) '.$subobj[$j]['SubObjectives'].' </td>';
for ($x = 0; $x < count($course); $x++) {
echo "<td><input name='check[]' type=checkbox value=c".$course[$x]->courseId."-o".$subobj[$j]['SubObjId']." id=checked></td>";
}
echo '</tr>';
}
}
}
}
}
?>
</tbody>
</table>
<button class="button" name= "submit" value= "Submit">Submit</button>
</form>
report-functions.php
if( isset( $_POST['submit'], $_POST['check'] ) ){
try{
require_once 'db-connect.php';
$conn = DatabaseConnection::getConnection();
$sql= " insert into `Report` (`ColRow`) values (:value) ";
$stmt = $conn->prepare( $sql );
if( $stmt ){
$conn->beginTransaction();
foreach( $_POST['check'] as $index => $value ) {
$result = $stmt->execute( [ ':value' => $value ] );
if( !$result ) {
echo '
<script>
alert("Error, please try submitting again. Error code 1");
window.history.back();
</script>';
}
}
$conn->commit();
echo '<script>
alert("Report was submitted successfully.");
window.location = ".../";
</script>';
}
} catch( Exception $e ){
$conn->rollback();
exit( $e->getMessage() );
}
I expect that once I submit the table, the table should load the same table with the checked checkboxes. I should be able to make the changes and submit the table over and over again.
Please comment if I need to provide any additional information.
When you display your page (in your first section of code), at some point you do this:
echo "<td><input name='check[]' type=checkbox value=c".$course[$x]->courseId."-o".$subobj[$j]['SubObjId']." id=checked></td>";
The value is set to:
value=c"c.$course[$x]->courseId."-o".$subobj[$j]['SubObjId']";
This value is where you get the checked or not value you mentioned in the comments (like c1-o1.1).
Right. So before you do that echo, add a new if condition.
$value = "c$course[$x]->courseId" . "-o$subobj[$j]['SubObjId']";
if (verify_checked($value)) {
$checked_code = "checked=\"checked\"";
}
else {
$checked_code = "";
}
echo "<td><input name='check[]' type=checkbox value=$value id=checked $checked_code ></td>";
The verify_checked(value) function does (from what I understand of your database, you keep the "grid location" of checked elements):
function verify_checked($value)
{
// Connect to the database if needed
// Perform: SELECT count($value) FROM Report
// If the result is >0, return TRUE
// Else return FALSE
}
The idea here is to query the database every time your are about to echo the <input> element.
Note for concatenating text, I find it more legible to put spaces around the . to clearly split what is part of the text and what is the concatenation dot.
As mentioned previously, indentation is critical for understanding of the different contexts. Until I indented your code, I had not realized how the different loops worked in relation to the others.
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);
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>
I wrote some code to display a html table with PHP.
It reads data from a file and checks whether the value is true or false.
The problem is the ugly appearance of the table at the end of the function:
True False
blue
Red
Red
blue
I would like to display the table like this:
True False
blue Red
blue Red
Also it displays the outcome before the function is finished c.q flush();
Here is the code:
?>
<table>
<tr>
<th>True</th>
<th>False</th>
</tr>
<?php foreach ($trimmed_array as $value) { ?>
<tr>
<?php if (check($value) == 0) { ?>
<td><?php print $value ?></td>
<td> </td>
<?php
} else { ?>
<td> </td>
<td><?php print $value ?></td>
<?php
}
sleep(1);
ob_flush();
flush();
} ?>
</table>
I realize this code outputs the table like the first example but I can`t seem to figure out how to change it to fit the second example?
Your code creates one table row per item in the array, so there will always be one blank column per row.
In the 'table' that you would like to display, the items in each row aren't related to each other.
So really you're creating 2 lists here, not a table as such.
I'd do something like this
<?php
$all_values = array('true' => array(), 'false' = array());
foreach($trimmed_array as $value){
if (check($value) == 0){
$all_values['true'][] = $value;
}else{
$all_values['false'][] = $value;
}
}
foreach($all_values as $name => $values){
?>
<ul class="<?php print $name;?>">
<?php
foreach($values as $value){
?>
<li><?php print $value; ?></li>
<?php
}
?>
</ul>
<?php
}
?>
You can then arrange your lists side by side with CSS
$true = array();
$false = array();
foreach ($trimmed_array as $value) {
if (check($value) == 0) {
$true[] = $value;
} else {
$false[] = $value;
}
}
for ($i = 0; $i < max(count($true), count($false)); $i++) {
echo '<tr>
<td>' . (isset($true[$i]) ? $true[$i] : '') . '</td>
<td>' . (isset($false[$i]) ? $false[$i] : '') . '</td>
</tr>';
}
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
}