Display data from SQL query in an HTML table in PHP - php

I retrieved a list of data from an SQL database and now I would like to display it in a neat table rather than in a list. I managed to find a way to do this (probably not very elegant, though), but the column headers seem to be offset and I have not idea how to fix this.
I'm completely new to PHP, so any hints on how to solve this will be much appreciated!
echo '<table>';
echo '<tr>';
echo '<th>';
echo '<td>Word</td>';
echo '<td>Frequency</td>';
echo '</th>';
echo '</tr>';
$response = $db->query("SELECT * FROM frequencies WHERE freq BETWEEN 900 AND 910 ORDER BY freq");
while ($row = $response->fetch())
{
echo '<tr>';
echo '<td>'.$row['word'].'</td>';
echo '<td>'.$row['freq'].'</td>';
echo '</tr>';
}
echo '</table>';
$response->closeCursor();

A <th> element is a table header element and should be used instead of <td> (table data) element in your header row - it should never be a wrapper around <td> elements.
echo '<table>';
echo '<tr>';
echo '<th>Word</th>';
echo '<th>Frequency</th>';
echo '</tr>';

I prefer combining php and html
<table >
<thead>
<tr>
<th >Word</th>
<th >Frequency</th>
</tr>
</thead>
<?php
$response = $db->query("SELECT * FROM frequencies WHERE freq
BETWEEN 900 AND 910 ORDER BY freq");
?>
<tbody>
<?php
while ( $row = $response->fetch()) {
?>
<tr>
<td><?php echo $row['word']; ?></td>
<td><?php echo $row['freq']; ?></td>
</tr>
<?php }
$response->closeCursor();
?>
</tbody>
</table>

Related

PHP returns incorrect HTML code ignoring some tags

I have the below code to display content from a database. The while loop is supposed to display data in a table row. The output is different: the data from the database are displayed before the table. The while seems to run and ignore the html tags, and then run again and ignore the variables.
PHP Code:
// Instantiate database
$database = new Database();
$db = $database->getConnection();
// List transactions without bundles
$query = "SELECT * FROM stock_trx WHERE bundleId IS NULL";
$statement = $db->prepare($query);
$statement->execute();
$n = $statement->rowCount();
if($n > 0){
echo "<table>
<thead>
<tr>
<th>Select</th>
<th>Date</th>
<th>Type</th>
<th>Quantity</th>
<th>Ticker</th>
<th>Amount</th>
<th>Currency</th>
</tr>
</thead>
<tbody>";
// Retrieve table content
while($row = $statement->fetch(PDO::FETCH_ASSOC)){
// Extract row
extract($row);
echo "<tr>".$id."</tr>";
echo "<tr>".$date."</tr>";
echo "<tr>".$type."</tr>";
echo "<tr>".$qty."</tr>";
echo "<tr>".$ticker."</tr>";
echo "<tr>".$amount."</tr>";
echo "<tr>".$currency."</tr>";
}
echo "</tbody></table>";
} else {
echo "No transaction";
}
HTML output:
<html>
<body>
12020-05-13 00:00:00BUYTEST1000022020-05-19 00:00:00SELTEST1200032020-05-24 00:00:00DIVTEST250<table>
<thead>
<tr>
<th>Select</th>
<th>Date</th>
<th>Type</th>
<th>Quantity</th>
<th>Ticker</th>
<th>Amount</th>
<th>Currency</th>
</tr>
</thead>
<tbody><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr>
</tbody>
</table>
</body></html>
Thank you
You need rows <tr> and cells <td> inside the row:
while($row = $statement->fetch(PDO::FETCH_ASSOC)){
// Extract row
extract($row);
echo "<tr>"; // start row
echo "<td>".$id."</td>";
echo "<td>".$date."</td>";
echo "<td>".$type."</td>";
echo "<td>".$qty."</td>";
echo "<td>".$ticker."</td>";
echo "<td>".$amount."</td>";
echo "<td>".$currency."</td>";
echo "</tr>"; // end row
}
echo "</tbody></table>";
Contrary to the other answer I would either do this, since you're using double-quotes:
echo "<tr>"; // start row
echo "<td>$id</td>";
// etc...
Or combine into one, maybe even one line:
echo "
<tr>
<td>$id</td>
<td>$date</td>
<td>$type</td>
<td>$qty</td>
<td>$ticker</td>
<td>$amount</td>
<td>$currency</td>
</tr>";
While some others have mentioned that you need TD tags, I'd just like to point out some weirder PHP-type things that may or may not help you now / in the future.
Your statement can be rewritten
<?php
while($row = $statement->fetch(PDO::FETCH_ASSOC)):
// Extract row
extract($row);?>
<tr>
<td><?php echo $id; ?>?</td>
<td><?php echo $date; ?>?</td>
<td><?php echo $type; ?>?</td>
<td><?php echo $qty; ?>?</td>
<td><?php echo $ticker; ?>?</td>
<td><?php echo $amount; ?>?</td>
<td><?php echo $currency; ?>?</td>
</tr>
<?php endwhile; ?>
This uses some lesser seen formats for using HTML in PHP files, but it should work never-the-less (tested locally with the PHP 7.4 CLI). Some people prefer it to having to use echo to output all of the HTML, but you do still have to have a bunch of echo statements to print the variables.
To reiterate, there's nothing wrong with any of the other answers, I just feel that in cases like this where you are using a bunch of HTML with PHP that this sort of notation can be a bit easier to work with.
As some people replied, the below tag is missing:
<td>

Total of column in displayed result in PHP

I have a table 'tblexam' which contains State,city,candidate.I want to fetch the data from this table using where clause.I am able to fetch the data but i want to add the sum of Candidate at the last row(As Shown In Picture) how can i do that .
$sql="SELECT *
FROM tblexam
WHERE state='UP'";
$cnt=1;
if($query->rowCount() > 0)
{
foreach($results as $result) {
$cnt=$cnt+1; ?>
<tr class="odd gradeX">
<td class="center"><?php echo htmlentities($cnt);?></td>
<td class="left"align="left"><?php echo htmlentities($result->state);?></td>
<td class="center" align="left"><?php echo htmlentities($result->city);?></td>
<td class="center"align="left"><?php echo htmlentities($result->candidate);?></td>
<?php } ?>
<td class="center"align="left"><?php echo htmlentities($result->Total);?></td>
</tbody>
</table>
Add total while iterating through rows and display it outside the loop, Sample code is given below
$sql = "SELECT * FROM tblexam WHERE city='UP'";
$result = $conn->query($sql);
$numRows = $result->num_rows;
if ($numRows> 0) {
$total = 0;
echo '<table border="1" cellpadding="5" cellspacing="0">';
echo '<tr>';
echo '<th>state</th>';
echo '<th>city</th>';
echo '<th>candidate</th>';
echo '</tr>';
while($row = $result->fetch_assoc()) {
$total+=$row['candidate'];
echo '<tr>';
echo '<td>'.$row['city'].'</td>';
echo '<td>'.$row['state'].'</td>';
echo '<td>'.$row['candidate'].'</td>';
echo '</tr>';
}
echo '<tr>';
echo '<td>Total</td>';
echo '<td> </td>';
echo '<td>'.$total.'</td>';
echo '</tr>';
echo '<table>';
}
Before you start looping the data you can create a variable which you set to 0, inside the loop you can add the result's total to this variable, after the loop, the variable will contain the grand total:
$total = 0;
foreach($results as $result) {
$total += (int)$result->Total;
...
}
// $total = 1425

PHP - Rating 1-5 in stars

<table>
<tr>
<th>name</th>
<th>startDate</th>
<th>rating</th>
<th>underlay</th>
<th>edges</th>
<th>grip</th>
<th>depth</th>
<th>length</th>
<th>height</th>
<th>realname</th>
</tr>
<?php
if(isset($_GET['DS'])){
$query='SELECT * FROM KundDetaljer where rspName = :DS';
$stmt = $pdo->prepare($query);
$stmt->bindParam(':DS', $_GET['DS']);
$stmt->execute();
foreach($stmt as $key => $row){
echo '<tr>';
echo "<td>".$row['rspName']."</td>";
echo "<td>".$row['startDate']."</td>";
echo "<td>".$row['rating']."</td>";
echo "<td>".$row['underlay']."</td>";
echo "<td>".$row['edges']."</td>";
echo "<td>".$row['grip']."</td>";
echo "<td>".$row['depth']."</td>";
echo "<td>".$row['length']."</td>";
echo "<td>".$row['height']."</td>";
echo "<td>".$row['realname']."</td>";
echo "</tr>";
}
}
echo "</table>";
?>
Hi, i'm a student in Sweden who is having a problem with making numbers to stars out of rating. The code above is the code that shows the rating from customers. When the comments from customers is made i want it to be showed as stars.
inside foreach (before any echo):
$stars = "";
for($i=0;$i<$row["rating"];$i++){
$stars .= "★";
}
Then instead of
echo "<td>".$row['rating']."</td>";
use
echo "<td>".$stars."</td>";

How do I make a MySQL infinite array table?

I am using this code to create an infinite table for my mysql queries:
<table cellspacing='0'> <!-- cellspacing='0' is important, must stay -->
<!-- Table Header -->
<thead>
<tr>
<th>User</th>
<th>SteamID</th>
<th>Banned by</th>
<th>Admin SteamID</th>
<th>Time Banned (min)</th>
<th>Reason</th>
</tr>
</thead>
<!-- Table Header -->
<!-- Table Body -->
<tbody>
<?php
echo '<tr>';
for($i = 0; $bans = mysqli_fetch_array($query2); $i = ($i+1)%3){
echo '<td>'.$bans['name'].'</td>';
echo '<td>'.$bans['steamid'].'</td>';
echo '<td>'.$bans['nameAdmin'].'</td>';
echo '<td>'.$bans['steamidAdmin'].'</td>';
echo '<td>'.$bans['time'].'</td>';
echo '<td>'.$bans['reason'].'</td>';
if($i == 2)
echo '</tr><tr>';
}
echo '</tr>';
?>
</tbody>
I got that code from Mysql fetch array, table results
It works fine, except it doesn't CORRECTLY go further down than 6 rows. The other rows for whatever reason are placed to the right of my last column as shown in this screenshot:
http://puu.sh/h0qZF/a12de1dd87.png
How can I fix this? Is there something wrong with my code? Why is it happening?
Well, your looping makes no sense. Using $i to inject new rows, like is done here, is not necessary; you can just loop over each row and then output it as a row:
<table>
<!-- <thead>...</thead> -->
<tbody>
<?php while ($bans = mysqli_fetch_array($query2)): ?>
<tr>
<td><?php echo $bans['name'] ?></td>
<td><?php echo $bans['steamid'] ?></td>
<td><?php echo $bans['nameAdmin'] ?></td>
<td><?php echo $bans['steamidAdmin'] ?></td>
<td><?php echo $bans['time'] ?></td>
<td><?php echo $bans['reason'] ?></td>
</tr>
<?php endwhile ?>
</tbody>
</table>
You are making two columns.
You have code that will print out the end of the table row every two sets of data:
if($i == 2)
echo '</tr><tr>';
It should just be echo '</tr><tr>';
Use a while loop as instructed here . So something like this:
$result = $conn->query($sql);
while($bans = $result->fetch_assoc()) {
echo '<td>'.$bans['name'].'</td>';
echo '<td>'.$bans['steamid'].'</td>';
echo '<td>'.$bans['nameAdmin'].'</td>';
}

PHP pagination table how to change the display to top to bottom

I am trying to create the PHP pagination table.. but in below format..
ID: data
Comments: data
Date: data
but now my table is like this:
ID Comments Date
data data data
By any chance anyone could let me know how to change it? .......my code is like this now:
<?
$connection=Mysql_connect('XX','XX','XX');
if(!$connection)
{
echo 'connection is invalid';
}
else
{
Mysql_select_db('XX',$connection);
}
//check if the starting row variable was passed in the URL or not
if (!isset($_GET['startrow']) or !is_numeric($_GET['startrow'])) {
//we give the value of the starting row to 0 because nothing was found in URL
$startrow = 0;
//otherwise we take the value from the URL
} else {
$startrow = (int)$_GET['startrow'];
}
//this part goes after the checking of the $_GET var
$fetch = mysql_query("SELECT * FROM products LIMIT $startrow, 10")or
die(mysql_error());
$num=Mysql_num_rows($fetch);
if($num>0)
{
echo "<table border=0 >";
echo "<tr><td>ID</td><td>Drug</td><td>quantity</td></tr>";
for($i=0;$i<$num;$i++)
{
$row=mysql_fetch_row($fetch);
echo "<tr>";
echo"<td>$row[1]</td>";
echo"<td>$row[2]</td>";
echo"<td>$row[3]</td>";
echo"<td >$row[5]</td>";
echo"</tr>";
}//for
echo"</table>";
}
//now this is the link..
echo 'Next';
$prev = $startrow - 10;
//only print a "Previous" link if a "Next" was clicked
if ($prev >= 0)
echo 'Previous';
?></td>
<td width="331"> </td>
</tr>
</table></td>
</tr>
</table>
</td>
</tr>
<?php
include("footer.php");
?>
sorry just figure out now..
$row=mysql_fetch_row($fetch);
echo "<tr>";
echo"<td>ID:$row[1]</td>";
echo "</tr>";
echo "<tr>";
echo"<td>Drug:$row[2]</td>"; echo "</tr>"; echo "<tr>";
echo"<td>QTY:$row[3]</td>"; echo "</tr>"; echo "<tr>";
echo"<td >Date:$row[5]</td>"
;echo "</tr>";
echo"</tr>"; echo"<tr height ='20'>";echo"</tr>";
echo"<tr >";echo"</tr>";echo"<tr >";echo"</tr>";
}//for
echo"</table>";
}
Oh, I got it now !
That you can achieve below way:
<table cellpadding="0" cellspacing="0">
<tr>
<th>ID</th>
<th>Comments</th>
<th>Date</th>
</tr>
<?php
if(mysql_num_rows($recordsets) > 0){
foreach ($recordsets as $recordset):
?>
<tr>
<td><?php echo $recordset['id']); ?></td>
<td><?php echo $recordset['comments']); ?></td>
<td><?php echo $recordset['date']); ?></td>
</tr>
<?php
endforeach;
} else {
?>
<tr>
<td colspan="3">No records found !</td>
</tr>
<?php
}
?>
</table>
Here, first row will be your table records header information and then loop through your records result sets.
Hope it helps you !

Categories