This question already has answers here:
check if variable empty
(12 answers)
Closed 4 years ago.
I have this following code:
$result = $conn->query($query);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc())
{
echo "<tr>";
echo "<td>" . preg_replace('/[^0-9]+/','',$row['total']) . "</td>";
echo "</tr>";
}
What I try to do is if the output is empty, then insert (-) character. Only if there is no value output.
I tried this:
$result = $conn->query($query);
if ($result->num_rows > 0) {
$total = $total ?? "" ?: "-";
while($row = $result->fetch_assoc())
{
echo "<tr>";
echo "<td>" . $total . "</td>";
echo "</tr>";
}
this replaces all outputs with (-).
How can I achieve this? please. thank you for your help!
Note that if the result of preg_replace('/[^0-9]+/','',$row['total']) is empty, then it should insert (-) character.
The inputs are like this:
100.
80.
70.
etc
Expected output would be something like this:
Total
100
90
-
80
70
-
10
You can check total value and replace it if it is empty. For example:
while($row = $result->fetch_assoc()) {
$total = empty($row['total']) ? '-' : preg_replace('/[^0-9]+/','',$row['total']);
echo "<tr>";
echo "<td>" . $total . "</td>";
echo "</tr>";
}
you can also use case statement in mysql
SELECT (CASE
WHEN total regexp '^[0-9]+$' THEN total
ELSE '-' END) as total
FROM `tbl_order`
where regexp '^[0-9]+$' matches whether variable total is numeric or not
by using case we check if total is numeric then print total otherwise -
Related
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>";
}
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.
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--;
}
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;
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.