PHP equation within html table row, or in database itself - php

I have a site with a CSV upload, which pushes everything in the CSV to a temp table and then splits into smaller tables.
Currently, I have a display page that displays all of that info in HTML tables. Some sections, however, need to have a formulaic representation. In other words, as seen in the screenshot below, meter volume is divided by tester volume and the sum of that is multiplied by the tester accuracy. That number is divided by 100 to give the corrected accuracy.
Here is the code I have but it's not loading my web page and I think the PHP might be wrong in establishing the variables:
<table style="width:100%; border:none;
border-collapse:collapse;">
<? php
$test1FormA = $row['test1MeterVol'] / $row['test1TesterVol'];
$test1FormB = $test1FormA * $row['test1Accuracy'];
$test1FinalForm = $test1FormB / 100;
?>
<tr>
<td style="border:none; text-align: left;">Meter Volume: </td>
<td><? echo $row['test1MeterVol'];?> </td>
</tr>
<tr>
<td style="border:none; text-align: left;">Tester Volume: </td>
<td><? echo $row['test1TesterVol'];?> </td>
</tr>
<tr>
<td style="border:none; text-align: left;">Tester Accuracy: </td>
<td><? echo $row['test1Accuracy'];?> </td>
</tr>
<tr>
<td style="border:none; text-align: left;">Corrected Accuracy: </td>
<td><? echo $test1FinalForm;?> </td>
</tr>
</table>
There is currently no corrected accuracy in the database, so I wanted to find either a way to do it per line, like above, or a way to do that upon every CSV upload. There are 8 tests, so it would have to do that formula for 8 different fields per 5 records in the CSV upon upload. I currently have the CSV uploading into the temp table with a large insert statement.
Is there a way to just do this in the table row with PHP?
UPDATE: Screenshot of new results
UPDATE: Code for averaging issue
<?php
$sum=0;
for($i=1; $i<=8; $i++){
$testFormA = $row["test".$i."MeterVol"] / $row["test".$i."TesterVol"];
$testFormB = $testFormA * $row["test".$i."Accuracy"];
$testFinalForm = $testFormB / 100;
$sum += $testFinalForm;
echo"$sum";
?>
<td><?php echo round($testFinalForm,3) ?>%</td>
<?php }
$average = $sum / 8;
echo"$average";
?>
<td><?php echo round($average,3)?> </td>

There are many ways to do what you need. But the most important part is that you will need a loop structure to build your table with a pretty code, without repeating everything over and over.
In your case, you can use the following code to build your whole last row for all 8 tests:
<?php for($i=1; $i<=8; $i++){
$testFormA = $row["test".$i."MeterVol"] / $row["test".$i."TesterVol"];
$testFormB = $testFormA * $row["test".$i."Accuracy"];
$testFinalForm = $testFormB / 100;
?>
<td><?php echo $testFinalForm ?></td>
<?php } ?>
Instead of accessing indexes like "test4MeterVol" you use $i to build the index string to access the right value in each loop iteration.
Doing the equations inside the loop will give you different values based on each test.
Based on this code and the way to build indexes to access your data you should be able to build the other rows, which are much simpler.

Related

A nested WHILE loop to fetch and display data from TWO tables

I'm in the process of building an entertainment website. It uses THREE MySQL tables; one called title, one called clips and one called dialogue.
I've been playing around all day with having my PHP fetch data from TWO of the tables (clips and dialogue) and output the content in a HTML table.
I've not had much luck and to cap it all, I was using a free host which has now reached its EP limit and although I've upgraded, I've got to wait 24 hours to try the code I've now come up with.
My question is, have I done it right? Will this collect basic information about the clip and then produce each line of the script in a new TR before going back to the start and collecting information for the next clip?
I really hope this makes sense.
I've tried researching this and have re-built my PHP from the ground up, ensuring that I annotate each section. Last time I checked, it still didn't work!
<table class='container'>";
##############################
# CLIPS QUERY & ECHOING HERE #
##############################
$clipsquery = "SELECT * FROM clips WHERE titleid=$mainurn ORDER BY clipid";
$result2 = mysqli_query($cxn, $clipsquery);
while ($row2 = mysqli_fetch_assoc($result2))
{extract ($row2);
echo "
<tr>
<td colspan='3' class='divider'></td>
</tr>
<tr>
<td class='description'>";
if ($epident == "")
{echo "";}
else
{echo "<span class='episode'>$epident</span>";}
echo "</td>
<td rowspan='2' style='text-align: right'><audio controls>
<source src='media/$clipid.mp3' type='audio/mpeg'>Your browser does not support the audio element.</audio></td>
<td rowspan='2' style='text-align: right'><a href='media/$clipid.mp3' download='$clipid.mp3'><img src='graphics/dl-icon.png' alt='Download Icon' title='Right-click here to download this clip to your computer.'></a></td>
</tr>
<tr>
<td class='description'>$clipsynopsis</td>
</tr>
<tr>
<td colspan='3'></td>
</tr>";
#################################
# DIALOGUE QUERY & ECHOING HERE #
#################################
$dialoguequery = "SELECT * FROM dialogue WHERE clipid=$clipid ORDER BY linenum";
$result3 = mysqli_query($cxn, $dialoguequery);
while ($row3 = mysqli_fetch_assoc($result3))
{extract ($row3);
echo "
<tr>
<td class='speaker'>$speaker:</td>
<td colspan='2' class='script'>$dialogue:</td>
</tr>";}}
echo "
</table>
I've got the site to work (sort of) but the formatting went wild and sometimes included clips from other sources not meant to be on the page!
There are some things I would change in your code. If you trust the variables going into your sql query then change your while loops:
while($row = $result->fetch_assoc()){
$fetchValue = $row['COLUMN_NAME'];
}
I would say you shouldn't be using extract here.
If the user is able to modify the variables going into your sql statement you should implement prepared statements. I would build a class/function and just call it when you need it.
From the HTML/CSS side its probably going to serve you better to use css div tables, especially if you are planning to make the site responsive down the line. This can convert yours
With regards to the queries, I'm not sure I understand the structure of your tables. If you want to keep playing around on your machine install a L/W/M/AMP stack depending on your operating system. See here for more information.
You only need one table where you store the data of clips.
First, you fetch the data into an array, then
you can loop through that array with foreach,
creating the table and filling it with data.
You can use an alternative syntax for foreach to make mixing PHP with HTML easier.
//Creating the array of clips
$clips = [];
$sql = "SELECT * FROM clips";
if($result = mysqli_query($db, $sql)) {
while($row = mysqli_fetch_assoc($result)) {
array_push($clips, $row);
}
}
?>
<!-- Looping through the array and creating the table -->
<table class="container">
<?php foreach ($clips as $clip): ?>
<tr>
<td colspan='3' class='divider'></td>
</tr>
<tr>
<td class='description'>
<span class='episode'><?php echo $clip["id"]; ?></span>
</td>
<td rowspan='2' style='text-align: right'>
<audio controls>
<source src='<?php echo "media/". $clip["id"]. ".mp3"; ?>' type='audio/mpeg'>
Your browser does not support the audio element.
</audio>
</td>
<td rowspan='2' style='text-align: right'>
<a href='<?php echo "media/". $clip["id"]. ".mp3"; ?>' download='<?php echo $clip["id"]. ".mp3"; ?>'>
<img src='graphics/dl-icon.png' alt='Download Icon' title='Right-click here to download this clip to your computer.'>
</a>
</td>
</tr>
<tr>
<td class='description'>
<?php echo $clip["sypnosis"]; ?>
</td>
</tr>
<tr>
<td class='speaker'>
<?php echo $clip["speaker"]; ?>
</td>
<td colspan='2' class='script'><?php echo $clip["dialogue"]; ?>
</td>
</tr>
<?php endforeach; ?>
</table>
You need 1 MySQL table (clips) with the 4 attributes.
You should consider using PDO over mysqli, because it's a better way of dealing with the database.
Also, template engines like Smarty can help you make the code more readable and modifiable, separating the application logic from the presentation logic.
you must use JOIN in your Sql query
SELECT
clips.clipid, clips.columnname,
dilogue.id, dialogue.columnname
FROM
clips JOIN dialogue ON
clips.clipid = dialogue.id
WHERE
clipid=$clipid
ORDER BY linenum
then you can use
while($row = mysqli_fetch_assoc($result)){
echo $row['column name in clips table'];
echo $row['column name in dialogue table'];
}
but you must use Prepared statements or
mysqli_real_escape_string()
to avoid Sql Injections
also open and close PHP tags before and after html)

How Can I nest two foreach to get right values output?

I have two foreach blocks to get some values from a web page (I'm scraping values from an HTML table).
<?php
include('../simple_html_dom.php');
$html = file_get_html('http://www.betexplorer.com/soccer/belgium/jupiler-league/results/');
foreach($html->find('td') as $e) {
echo $e->innertext . '<br>';
}
foreach( $html->find('td[data-odd]') as $td ) {
echo $td->attr['data-odd'].PHP_EOL;
}
?>
and this is my HTML code:
<tr class="strong">
<td class="first-cell tl">
Waasland-Beveren - Anderlecht
</td>
<td class="result">
1:0
</td>
<td class="odds best-betrate" data-odd="5.97"></td>
<td class="odds" data-odd="4.21"></td>
<td class="odds" data-odd="1.51"></td>
<td class="last-cell nobr date">21.02.2016</td>
</tr>
<tr class="">
<td class="first-cell tl">
Waregem - KV Mechelen
</td>
<td class="result">
2:3
</td>
<td class="odds" data-odd="1.83"></td><td class="odds" data-odd="3.71"></td>
<td class="odds best-betrate" data-odd="3.99"></td>
<td class="last-cell nobr date">21.02.2016</td>
</tr>
In this way, in my output, I get before values from the first foreach and, after, values from the second. I'd like to get values together in the right order. For example:
21.02.2016 Waasland-Beveren - Anderlecht 1:0 5.96 4.20 1.51
21.02.2016 Waregem - KV Mechelen 2:3 1.83 3.71 3.98
If they have the exact (count) or (length). Use the normal for after you assign them to two variables.
$td = $html->find('td');
$attr = $html->find('td[data-odd]');
for($i=0; $i < count($td); $i++)
echo $td[$i]->innertext."<br/>".$attr[$i]->attr['data-odd'].PHP_EOL;
Update:
You want to reorder the tds you received from the HTML file, that means you have to think of another logic in how to retrieve them. This updated code is very specific to your case:
$match_dates = $html->find("td[class=last-cell nobr date]"); // we have 1 per match
$titles = $html->find("td[class=first-cell tl]"); // 1 per match
$results = $html->find("td[class=result]"); // 1
$best_bets = $html->find("td[class=odds best-betrate]"); // 1
$odds = $html->find("td[class=odds]"); // 2
// Now to output everything in whatever order you want:
$c=0; $b=0; // two counters
foreach($titles as $match)
echo $match_dates[$c]->innertext." - ".$match->innertext." [".$results[$c]->innertext."] - Best bet rate: ".$best_bets[$c++]->attr['data-odd']." - odds: ".$odds[$b++]->attr['data-odd'].", ".$odds[$b++]->attr['data-odd']."<br/>";

create horizontal bar chart

I want to make a horizontal bar chart in a web-page using php,mysql,javascript,css,html and 'wamp server',editor: 'Macromedia Dreamweaver',browser: 'Mozilla Firefox';
i want to read data(semister results) from table,and display data through bar chart like,
Database name exam
Table name 'sem_result' contain following columns>> regno[Primary key], uid, reg_date, exam_date, sem, result;
php code is::
<?php
// Connect to server
$cn=mysql_connect("localhost", "root", "");
//Connect to Database
mysql_select_db("exam") or die(mysql_error());
//sql query
$sql="SELECT result FROM sem_result WHERE uid=11111";
//collect results
$result=mysql_query($sql,$cn);
//read data if found
$counter=0;
while($rd=mysql_fetch_array($result))
{
$sem_result[$counter]=$rd[0]; //save sem results into array
$counter=$counter+1;
}
//display
echo "<table>
<tr>
<td>sem1</td>
<td width='100px'>
<img src='img/menu_back.png' width='".$sem_result[0]."%' height='15px'/>
</td>
<td>".$sem_result[0]."%</td>
</tr>
<tr>
<td>sem2</td>
<td width='100px'>
<img src='img/menu_back.png' width='".$sem_result[1]."%' height='15px'/>
</td>
<td>".$sem_result[1]."</td>
</tr>
</table>";
//close database
mysql_close($cn);
?>
if results are 78.95%,78.10% ,bar chart shows both result are equal, i.e 78%; image width become 78%,not 78.95% please help to fix this problem.
change table name and column name and progress.png image.
after that use it.
`
<?php $s="select count(*) as tnum from leakage";
$r=mysql_query($s) or die (mysql_error());
while($rw=mysql_fetch_array($r))
{
echo $tno=$rw['tnum'];
}
?>
<table class="table table-hover">
<thead>
<tr>
<th>DEPARTMENT</th>
<th>No.Of Leakage</th>
</tr>
</thead>
<?php
$sql1="select dept,count(dept) as total from leakage where dept='winding'";
$result1=mysql_query($sql1) or die(mysql_error());
while($row=mysql_fetch_array($result1))
{
$dept=$row['dept'];
$tot=$row['total'];
}
?>
<tr>
<td><?php echo $dept; ?></td>
<td width="100%"><img src="assets/images/progress.png" width="<?php echo (($tot/$tno)*100);?>" height="20px"><?php echo $tot;?>%</td>
</tr>
<?php
$sql2="select dept,count(dept) as total from leakage where dept='spining'";
$result2=mysql_query($sql2) or die(mysql_error());
while($row=mysql_fetch_array($result2))
{
$dept=$row['dept'];
$tot=$row['total'];
}
?>
<tr>
<td><?php echo $dept; ?></td>
<td width="100%"><img src="assets/images/progress.png" width="<?php echo (($tot/$tno)*100);?>" height="20px"><?php echo $tot;?>%</td>
</tr>
<?php
$sql5="select count(dept) as total from leakage";
$result5=mysql_query($sql5) or die(mysql_error());
while($row=mysql_fetch_array($result5))
{
$tot=$row['total'];
}
?>
<tr>
<td>Total</td>
<td width="100%"><img src="assets/images/progress.png" width="<?php echo $tot;?>" height="20px"><?php echo $tot; ?></td>
</tr>
</table>
`
As #hakre already pointed out, you can't get any more precise than a single pixel or percentage, ie you can't have 78.5px or 78.5%... however, you still have some options without javascript. First, I'm not sure why you are using an image for the green bar, why not just pure html/css? Either way, here's my suggestion:
Get the total width of the bar graph, from 0 - 100, in pixels. Just by eyeballing the image you posted, I'm gonna call it 325px:
$total_width = '325';
Then, set each bar's width as such:
$bar_width = round($total_width * ($sem_result[0] / 100));
This way, a stored value of 78.10% will end up as 254px, and 78.95% will be 257px. It is still not the exact percentage, but it is closer. The longer the total width of your graph, the more precise you calculation will be.

Odd and Even Rows for a table

I have a table that get its rows from a MYSQL database
<table id="table1">
<?php
// Connect to database server
mysql_connect("localhost", "root", "asnaeb") or die (mysql_error ());
// Select database
mysql_query("SET NAMES `utf8`"); // UTF 8 support!!
mysql_select_db("scores") or die(mysql_error());
// SQL query
$strSQL = "SELECT * FROM latest";
// Execute the query (the recordset $rs contains the result)
$rs = mysql_query($strSQL);
// Loop the recordset $rs
// Each row will be made into an array ($row) using mysql_fetch_array
while($row = mysql_fetch_array($rs)) {
// Write the value of the column FirstName (which is now in the array $row)
?>
<?php echo $row['Header'].""; ?>
<tr>
<td id='date'><?php echo $row['Date'].""; ?></td>
<td id='time'><?php echo $row['Time'].""; ?></td>
<td id='hometeam'><?php echo $row['HomeTeam'].""; ?></td>
<td id='score'><?php echo $row['Score'].""; ?></td>
<td id='awayteam'><?php echo $row['AwayTeam'].""; ?></td>
<td id='other'><?php echo $row['Other'].""; ?></td>
</tr>
<?php } mysql_close(); ?>
</table>
i have 2 css class called "A" and "B" for Odd Rows and Even Rows
i currently getting this done by replacing <tr> with <tr class='<?php echo $row['Row'].""; ?>'> and i have in my Database table a column "Row" which i add in A or B for even or odd row... the problem is if i wanna delete or add a new row between one of these i will have to change all the A and B in the other.
I have seen in another questions many way to do that in javascript or jquery but for a normal table with TR's which is not my case...(tried some of these scripts but couldn't get it fixed)
So what i want an easier way to do that Even and Odd rows, Thanks!
do it in CSS way (no inline class) once and for all:
in CSS:
#table1 tr:nth-child(odd) td { background-color:#ebebeb }
#table1 tr:nth-child(even) td { background-color:#0000ff }
in your HTML:
<table id="table1">
thats it, no matter if your table rows are removed/or not.
You can add those classes using jQuery easily like this
$(function(){
$('#table1 tr:odd').addClass('A');
// for even
$('#table1 tr:even').addClass('B');
});
Why didn't you use modulo in your while loop ? It's a better way than store your class in your database... :
$i = 0;
while($row = mysql_fetch_array($rs)) {
// Write the value of the column FirstName (which is now in the array $row)
?>
<?php echo $row['Header'].""; ?>
<tr class="<?php echo $i%2 == 0 ? "class_A" : "class_B" ; $i++;?>" >
<td id='date'><?php echo $row['Date'].""; ?></td>
<td id='time'><?php echo $row['Time'].""; ?></td>
<td id='hometeam'><?php echo $row['HomeTeam'].""; ?></td>
<td id='score'><?php echo $row['Score'].""; ?></td>
<td id='awayteam'><?php echo $row['AwayTeam'].""; ?></td>
<td id='other'><?php echo $row['Other'].""; ?></td>
</tr>
<?php } mysql_close(); ?>
<?php
$class="odd"
while($row = mysql_fetch_array($rs)) {
$class = ($class=='even' ? 'odd' : 'even');
?>
<tr class="<?php echo $class">
...
</tr>
<?php } ?>
There are many ways to do this, PHP, Javascript and even pure CSS. Here's the PHP way to add a class to every other row:
while($row = mysql_fetch_blahblah()) {
$i = 0; ?>
<tr class="<?php echo $i % 2 == 0 ? 'class1' : 'class2';?>">
<td>....</td>
</tr>
<?php
$i++; // increment our counter
}
Basically the modulus operator returns the remainder of dividing the nubmers either side of it, so for example 3 % 2 == 1, 4 % 2 == 0, 5 % 2 == 1, so we can tell if $i is odd or even and alternate the classes added to the <tr>.
IMHO you want to either do it this way for 100% guarantee it will work (no browser dependencies) or if you design your app for modern browsers go for the CSS route.

basic php form help (currency display)

You guys were very helpful yesterday. I am still a bit confused here though.
I want to make it so that the numbers on the rightmost column are rounded off to the nearest dollar:
http://www.nextadvisor.com/voip_services/voip_calculator.php?monthlybill=50&Submit=Submit
the code for the table looks like this:
I want $offer[1,2,3,4,5,6,7]calcsavingsann to be rounded, how can do this?
<table width="100%;" border="0" cellspacing="0" cellpadding="0"class="credit_table2" >
<tr class="credit_table2_brd">
<td class="credit_table2_brd_lbl" width="100px;">Services:</td>
<td class="credit_table2_brd_lbl" width="120px;">Our Ratings:</td>
<td class="credit_table2_brd_lbl" width="155px;">Monthly VoIP Bill:</td>
<td class="credit_table2_brd_lbl" width="155px;">Annual Savings:</td>
</tr>
<?php
$offer1price="24.99";
$offer2price="20.00";
$offer3price="21.95";
$offer4price="23.95";
$offer5price="19.95";
$offer6price="23.97";
$offer7price="24.99";
$offer1calcsavings= $monthlybill - $offer1price;
$offer2calcsavings= $monthlybill - $offer2price;
$offer3calcsavings= $monthlybill - $offer3price;
$offer4calcsavings= $monthlybill - $offer4price;
$offer5calcsavings= $monthlybill - $offer5price;
$offer6calcsavings= $monthlybill - $offer6price;
$offer7calcsavings= $monthlybill - $offer7price;
$monthybill="monthlybill";
$offer1calcsavingsann= $offer1calcsavings * 12;
$offer2calcsavingsann= $offer2calcsavings * 12;
$offer3calcsavingsann= $offer3calcsavings * 12;
$offer4calcsavingsann= $offer4calcsavings * 12;
$offer5calcsavingsann= $offer5calcsavings * 12;
$offer6calcsavingsann= $offer6calcsavings * 12;
$offer7calcsavingsann= $offer7calcsavings * 12;
$re=1;
$offer ='offer'.$re.'name';
$offername= ${$offer};
while($offername!=""){
$offerlo ='offer'.$re.'logo';
$offerlogo=${$offerlo};
$offerli ='offer'.$re.'link';
$offerlink=${$offerli};
$offeran ='offer'.$re.'anchor';
$offeranchor=${$offeran};
$offerst ='offer'.$re.'star1';
$offerstar=${$offerst};
$offerbot='offer'.$re.'bottomline';
$offerbottomline=${$offerbot};
$offerca ='offer'.$re.'calcsavings';
$offercalcsavings=${$offerca};
$offerpr ='offer'.$re.'price';
$offerprice=${$offerpr};
$offersavann ='offer'.$re.'calcsavingsann';
$offercalcsavingsann=${$offersavann};
echo '<tr >
<td >
<a href="'.$offerlink.'" target="blank"><img src="http://www.nextadvisor.com'.$offerlogo.'" alt="'.$offername.'" />
</a>
</td>
<td ><span class="rating_text">Rating:</span>
<span class="star_rating1">
<img src="http://www.nextadvisor.com'.$offerstar.'" alt="" />
</span>
<br />
<div style="margin-top:5px; color:#0000FF;">
Go to Site
<span style="margin:0px 7px 0px 7px;">|</span>Review
</div> </td>
<td >$'.$offerprice.'</td>
<td >$'.$offercalcsavingsann.'</td>
</tr>';
$re=$re+1;
$offer ='offer'.$re.'name';
$offername= ${$offer};
}
?>
</table>
Do you want rounded up/down/truncated to the nearest dollar?
Here are some suggested functions you can use:
Rounding
round
floor
ceil
Formatting/Truncating
sprintf
Grepsedawk's answer is good; the only thing I would add is that rather than displaying $336.6, for example, you could could use number_format to output $336.60.
(I know this wasn't your question, but looking at the link, I thought that might be useful for you.)
Edit - Thanks to Andy for suggesting money_format instead.
money_format() is a function that returns a string value of a formatted number. You have control over the formatting and, obviously, your number. A simple example, if you have your value in the variable $myNumber, you could incorporate the result into a given table's data cell like so;
<?php echo ("<td>".money_format('%n',$myNumber)."</td>"); ?>
And you would need to do this for every value, e.g. via a for loop if you had all your values in an array. The n here is one of the formatting options - there are several. A good place to look would be on the PHP web page at http://au2.php.net/manual/en/function.money-format.php
Hope this helps.
I can't seem to get the usage right. The way I am using echo is
echo '<tr >
<td ><img src="http://www.nextadvisor.com'.$offerlogo.'" alt="'.$offername.'" /></td>
<td ><span class="rating_text">Rating:</span><span class="star_rating1"><img src="http://www.nextadvisor.com'.$offerstar.'" alt="" /></span><br />
<div style="margin-top:5px; color:#0000FF;">Go to Site<span style="margin:0px 7px 0px 7px;">|</span>Review</div> </td>
<td >$'.$offerprice.'</td>
<td >$'.$offercalcsavingsann.'</td>
</tr>';
I put the "set locale" up where the
"<?php"
is. I don't understand how to write it, and every way I do just returns an error.

Categories