PHP built html table - php

I'm using the code below to build a table, but because the values in my database table are constantly incrementing, I'm doing some math to work out differences in values (numerically) but this has screwed up the table layout somehow. I've included a screenshot so you can see that the first row beneath the table header is just not right.
$column is a $_GET value from the user.
$sql = "select * from (select * from mash order by tstamp desc limit 10) s order by s.id";
$result = mysql_query($sql);
$previous = 0;
$firstRun = true;
echo "<table id='dataTable' border='1'>";
echo "<tr><th>Date</th>
<th>Value</th></tr>";
while($row = mysql_fetch_array($result)){
$difference = $row[$column] - $previous;
if (!$firstRun)
echo "<tr><td>" . date("G:i:s", strtotime($row["tstamp"])) . "</td>";
echo "<td>" . $difference . "</td></tr>";
$previous = $row[$column];
$firstRun = false;
}
echo "</table>";
My question: Can anyone spot from the code, why the first row would come out like this?

The problem comes from this line:
if (!$firstRun)
echo "<tr><td>" . date("G:i:s", strtotime($row["tstamp"])) . "</td>";
If you don't want to display the first line, use the brackets:
if (!$firstRun){
echo "<tr><td>" . date("G:i:s", strtotime($row["tstamp"])) . "</td>";
echo "<td>" . $difference . "</td></tr>";
}

It's your "if" statement. It doesn't echo anything on the first run, so the starting tr and td don't get echoed, so you end up with an incorrect row (ended with the /tr tag) containing only a single td value. Did you mean to put brackets around the two echo statements so that they only happen when firstrun is false?

first of all, where is $column defined ?
$difference = $row[$column] - $previous;
second, this is only executed as of the second iteration
if (!$firstRun)
echo "<tr><td>" . date("G:i:s", strtotime($row["tstamp"])) . "</td>";
This means that the first time in the while loop, you are not creating the table row <tr> , although I'm guessing the browser is able to "fix" the missing tag, but this would be the reason why -32722 appears in the first column.

Related

Use php to find specific values in results of mysql query

I have an sql query that looks like this:
//do a query to find all the samples in the currently selected rack
$sql = "SELECT SampleID, ColumnNumber, RowNumber FROM Samples WHERE Rack = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $rack);
$stmt->execute();
$rackContents = $stmt->get_result();
In each rack, a ColumnNumber and RowNumber combination describes a position in the rack, starting with:
ColumnNumber = 1, RowNumber = 1 then
ColumnNumber = 2, RowNumber = 1
and so on until (for example, in a 10x10 rack)
ColumnNumber = 10, RowNumber = 10.
I want to display the SampleIDs in each position of the rack in a table. Using a nested loop, I can draw a table that has a <td> for each rack position. What I can't figure out is how to display the SampleID based on the ColumnNumber and RowNumber combination for each position.
This is how I build the table:
//start a loop that visits each row
$rownumber = 1;
while ($rownumber <= $numberofrows){
//start a loop that visits each column
//start a row
echo "<tr>";
$columnnumber = 0;
while ($columnnumber <= $numberofcolumns){
if ($columnnumber == 0){
echo "<td>" . $rownumber . "</td>";
}
else{
//find the sample number for the relevant column and row
//inside the array we got in an sql query earlier, $rackContents
echo "<td>" . x . "</td>";
//What do I put in place of the x to output the appropriate
//SampleId for the ColumnNumber/RowNumber combo?
}
$columnnumber++;
}//end the columnnumber loop
//end the row
echo "</tr>";
$rownumber++;
}//end the rownumber loop
I've been looking at array_search, but I just can't get anywhere.
If I am understanding you correctly I think you just need to fetch the array from your result. Although I am not sure this is the result you actually want.
while ($rackContent = $rackContents->fetch_array(MYSQLI_NUM))
$rownumber = 1;
while ($rownumber <= $numberofrows){
echo "<tr>";
$columnnumber = 0;
while ($columnnumber <= 3){
if ($columnnumber == 0){
echo "<td>" . $rownumber . "</td>";
} else {
echo "<td>" . $rackContent['SampleID'] . "</td>";
}
$columnnumber++;
echo "</tr>";
$rownumber++;
}
}
But I think you probably want something more like this.
while ($rackContent = $rackContents->fetch_array(MYSQLI_NUM))
echo "<tr>";
echo "<td>" . $rownumber . "</td>";
echo "<td>" . $rackContent['SampleID'] . "</td>";
echo "<td>" . $rackContent['ColumnNumber'] . "</td>";
echo "<td>" . $rackContent['RowNumber'] . "</td>";
echo "</tr>";
}

Adding total of array in php?

I have a database and PHP file which outputs a module catogaries by the year the module was taken in. accompanying this is how much the module is worth.. eg Computer Science 10. The output on the screen needs to have the TOTAL of the points within that YEAR
So it looks like this:
2001/02
cs 10
bi 10
chem 10
total 30
This is all fine and works APART from if there is more years like this:
2001/02 0 points
2002/03 120 points
2003/04 120 points
But there is points in 2001/02 but the code seems to overwrite this before outputting it.
Here is the PHP code:
$points = array();
while ($row = mysql_fetch_array($result)) {
if ($year != $row["ayr"]) {
echo "<tr><th colspan='3'><b>" . $row["ayr"] . "</b></th></tr>";
$year = $row["ayr"];
echo "<td align='right'><b> Total Module Points: ".array_sum($points)."<td></b>";
$points = array();
}
if ($year = $row["ayr"]) {
array_push($points, $row["credits"]);
}
echo "<tr>";
echo "<td>" . $row["mid"] . "</td>";
echo "<td>" . $row["mtitle"] . "</td>";
echo "<td>" . $row["credits"] . "</td>";
echo "<tr>";
if ($year != $row["ayr"]) {
echo "<td align='right'> Total Module Points: ".array_sum($points)."<td>";
}
}
So the code gets the student number, output each module by year and then adds up the module points and gives a total but I cannot get the first table to work
regards
Maybe this causes your problem?
if ($year = $row["ayr"]) {
array_push($points, $row["credits"]);
}
Basically, $year will always be equal to $row["ayr"], is this a desired behavior?
The 'equal' comparison operator is '==' as stated before.

php make html table rows equal

I am getting data from a my database. There is a admin panel also where people can add data to the database. The data gets on the page but some of the rows(<tr>) have less table data tags(<td>) than others. thus the table is not justified. Is there a way to add empty <td> to rows that need them? I have tried everything but i can't figure it out.
Picture on how the table looks at the moment:
The green numbers are the total sum of points but it's not clear because the table rows are jagged. How to fix tis?
If there is a jQuery solution that's also fine.
my code:
echo "<table class=\"zebra1\">";
echo "<th>N. </th>" . "<th>Team name: </th>" . "<th colspan=\"5\">Points: </th>" . "<th>Sum: </th>";
$numbering =1;
$query2 = $db->prepare("SELECT pisteet_1 As PIY, pisteet_2 as PIK, nimi As NIM, opisto As OPI, pisteet.kaupunki_id As KA FROM
pisteet INNER JOIN joukkueet ON joukkueet.id = pisteet.team_id INNER JOIN oppilaitokset ON oppilaitokset.opisto_id = joukkueet.opisto_id ORDER BY team_id ASC");
$query2->execute();
$results = $query2->fetchAll();
$tableD = array();
foreach ($results as $key) {
$tableD[$key['NIM']][] = array('PIY'=>$key['PIY'],'PIK'=>$key['PIK'],'KA'=>$key['KA'], 'OPI'=>$key['OPI']);
}
foreach($tableD as $teamN=>$values2){
//Echoing the Team name
echo "<tr class=\"all " . $values2[0]['KA'] . "\">";
echo "<td>" . $numbering . "</td>";
echo "<td>" . $teamN ."<span>" . $values2[0]['OPI'] ."</span></td>";
$sum1=0;
$sum2=0;
//Echoing the points
foreach($values2 as $v2){
echo "<td class=\"points\">" . $v2['PIY'] . "/" . $v2['PIK'] . "</td>";
$sum1 +=$v2['PIY'];
$sum2 +=$v2['PIK'];
}
//Echoing the total sum of points
echo '<td class="Sum">'.$sum1.'/'.$sum2."</td>";
echo "</tr>";
$numbering ++;
}
echo '</table>';
I have a variable named: $colspancalculated that has the longest row: at the moment it stores the value 5.
Assuming you have a fixed number of columns (I assume this because you've got a colspan on your table header cell), you need to output the td elements as you are doing, or output blank cells if the records don't exist.
Consider something like this instead of your foreach:
// Echoing the points - as you mention in your comment, you've calculated
// the maximum column size as $colspancalculated - so you that as your upper limit
for($i = 0; $i < $colspancalculated; $i++) {
if(!isset($values2[$i]['PIY'])) {
// This record doesn't exist! Output a blank cell
echo '<td></td>';
continue;
}
// Otherwise, output the cell and do your calculations
echo '<td class="points">' . $values2[$i]['PIY'] . '/' . $values2[$i]['PIK'] . '</td>';
$sum1 += $values2[$i]['PIY'];
$sum2 += $values2[$i]['PIK'];
}
Instead of a foreach loop, use a for loop -- or, since you have to work with an iterator, anyway, just do:
$i = $numberOfColumnsLeftAtThisPointInYourScript
foreach($values2 as $v2){
echo "<td class=\"points\">" . $v2['PIY'] . "/" . $v2['PIK'] . "</td>";
$sum1 +=$v2['PIY'];
$sum2 +=$v2['PIK'];
$i--;
}
while($i > 0){
echo '<td> </td>';
$i--;
}

Formatting a mysql number from a select statement into php

I am using mysql 5.1 database and have a # of fields in them that look like this for format:
1234567
When I output them to via php, I would like them formatted like this:
1,234,567
There are no decimals involved.
The select statement is pulling 30 records from my database. Each record has (2) fields that I need formatted thus. Weight and Cost as well as 16 other fields that I need, but do not need formatting. They are being read and entered int a table.
Suggestions?
Note:
Data Fields: Cost Weight
Table: Warships
Current Select statement:
$result = mysql_query('SELECT * FROM `Warships` WHERE `Type` = "BC" ');
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['ID'] . "</td>";
echo "<td>" . $row['SHIP CLASS'] . "</td>";
echo "<td>" . $row['CAT'] . "</td>";
echo "<td>" . $row['Type'] . "</td>";
echo "<td>" . $row['WEIGHT'] . "</td>";
echo "<td>" . $row['Cost'] . "</td>";
I think PHP's number_format is what you need.
$num = number_format(1234567);
echo $num; // 1,234,567
If only one parameter is given, number will be formatted without decimals, but with a comma (",") between every group of thousands. More info from PHP API
You're looking for the number_format function. Pass your number to it as the first parameter and it will add in a comma for the thousands separator.
Example:
echo "<td>" . number_format($row['Cost']) . "</td>";
number format
$num_format = number_format(1234567);
echo $num_format ; // 1,234,567

Math operation in PHP & MySQL

I'm creating a table using a PHP from the MySQL query which return a total count of rows from two columns in the database, "total_tr" and "total_rc".
I've already done and successfully view the count in the PHP table, the coding is:
while($row = mysql_fetch_array($result))
{
echo "<tbody>";
echo "<tr>";
echo "<td>Zone</td>";
echo "<td>" . $row['segment_code'] . "</td>";
echo "<td>" . $row['COUNT(total_tr)'] . "</td>";
echo "<td>" . $row['COUNT(repeat_rc)'] . "</td>";
echo "</tr>";
echo "</tbody>";
}
My problem now is, I want to take the total count value of "total_tr", divided with total count of "repeat_rc" and multiply with 100 to get the percentage of total_rc.
Any ideas on how can I do that?
$myresult = $row['COUNT(total_tr)'] / $row['COUNT(repeat_rc)'] * 100;
Keep a running count as you echo the rows
$total_tr = 0;
$total_rc = 0;
while($row = ...) {
$total_tr += $row['COUNT(total_tr)']);
$total_rc += $row['COUNT(repeat_rc)']);
... html here ...
}
echo $total_tr / $total_rc * 100;

Categories