fetch tags inside php - php

I am trying to get some div tags inside my php. The original code that is working looks like this:
echo "Date: ".$row{'date'}."<br>"."Day: ".$row{'day'}."<br>"."From Time: ".$row{'fromtime'}."<br>"."To Time: ".$row{'totime'}; //display the results
When I run this code, the data is gonna be below each other. I would like that each output from the database, is coming out in a row and in some div tags, so I can control it. I have tried to make it, but I am really in doubt how the syntax are?
<?php
echo "<div class="column1">""Date: ".$row{'date'}"</div>";
echo "<div class="column2">""Day: ".$row{'day'}"</div>";
echo "<div class="column3">""From Time: ".$row{'fromtime'}"</div>";
echo "<div class="column4">""To Time": ".$row{'totime'}"</div>";
?>
This dosent work. Does anybody know how I can solve this?
New code:
Thanks a lot for both your answers. I am actually thinking of putting in a table instead. When I print out the div, it looks like this:
http://postimg.org/image/jq60jujv1/
So I guess it would be something with
//fetch the data from the database
Print"<h3>Return from database:</h3>"."<br>";
print '<table border="1">';
print '<tr>';
print '<td>date</td>';
print '<td>day</td>';
print '<td>fromtime</td>';
print '<td>totime</td>';
print '</tr>'."<br>";
print '</table>'."<br>";
while ($row = mysql_fetch_array($result)) {
print "<tr>"."<td>"."Date: ".$row{'date'}."</td>"."</tr>";
print "<tr>"."<td>"."Day: ".$row{'day'}."</td>"."</tr>";
print "<td>"."From Time: ".$row{'fromtime'}."</td>";
print "<td>"."To Time: ".$row{'totime'}."</td>"."<br>";
}
or?
Best Regards
Mads

try this instead of yours,
<?php
echo "<div class='column1'>"."Date: ".$row{'date'}."</div>";
echo "<div class='column2'>"."Day: ".$row{'day'}."</div>";
echo "<div class='column3'>"."From Time: ".$row{'fromtime'}."</div>";
echo "<div class='column4'>"."To Time: ".$row{'totime'}."</div>";
?>

Because of the wrapping quotation marks you use for echo ".." you can not use the same quotation marks inside that string:
echo "<div class="column1">""Date: ".$row{'date'}"</div>";
^--- string ended
You can solve this in several ways, using single quotation marks inside is already suggested, but you can also escape the ones you are currently using:
echo "<div class=\"column1\">Date: ".$row{'date'}."</div>";
^ ^
You can avoid all these problems by not using echo for output of all markup, but rather start/end php tags the place you actually want to print
variables or do some logic:
<div class="column1">Date: <?php echo $row{'date'}; ?></div>
Output as table
A HTML table use the <table> and </table> tags,
<tr> is a table row, <th> for table
headers and <td> for regular table cells.
<?php
/* the code block where you connect to db etc.. */
?>
<table>
<!-- headers -->
<tr>
<th>Date</th>
<th>Day</th>
<th>From</th>
<th>To</th>
</tr>
<!-- Now a row for each new set of data, here you probably need to
loop through some data set you retrieve from the database -->
<?php while($row = mysql_fetch_array($result)): ?>
<tr>
<td><?php echo $row{'date'};?></td>
<td><?php echo $row{'day'};?></td>
<td><?php echo $row{'fromtime'};?></td>
<td><?php echo $row{'totime'};?></td>
</tr>
<?php endwhile; ?>
</table>

Try this
<?php
echo "<div class='column1'>Date: ".$row{'date'}."</div>
<div class='column2'>Day: ".$row{'day'}."</div>
<div class='column3'>From Time: ".$row{'fromtime'}."</div>
<div class='column4'>To Time: ".$row{'totime'}."</div>";
?>
Edit:
If you want output as table
<table>
<tr>
<th>Date</th>
<th>Day</th>
<th>From Time</th>
<th>To Time</th>
</tr>
<?php
foreach($result as $row){
echo "<tr><td>".$row{'date'}."</td>
<td>".$row{'day'}."</td>
<td>".$row{'fromtime'}."</td>
<td>".$row{'totime'}."</td></tr>";
}
?>
</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>

Display data from SQL query in an HTML table in 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>

Creating a table in HTML to display the result of a query in MySQL

I want to create a PHP page to display the results of a query in a MySQL database under the format of a table. By spending quite some time on different forums, I ended with something that is somehow satisfying me but that is strongly affecting the design and the layout of my webpage. Due to the fact that I wrote the code by a test-fail strategy, it is far from being straightforward and I am sure it is possible to shorten and simplify it and, therefore, make it more compatible with the format of my webpage. Could anybody have a look at it and give some suggestions of general interest about how to solve this kind of issues?
<div id="main">
<?php
require_once('../mysqli_connect.php');
$response = $db->query("SELECT * FROM metabolite");
echo '<table align="center" cellspacing="2" cellpadding="5" border = "1">
<tr><td align="center"><b>Metabolites</b></td>
<td align="center"><b>KEGG Id</b></td>
<td align="center"><b>Synonyms</b></td></tr>';
while ($data = $response->fetch())
{
?>
<tr><td align="left">
<?php echo $data['Metabolite_name']; ?></td>
<td align="left">
KEGG: <?php echo $data['Synonyms']; ?></td>
<td align="left">
<?php echo $data['Synonyms']; ?></td>
</tr>
<?php
}
$response->closeCursor();
?>
</div>
I thank you in advance for all your effort and your help.
Tom.
There's no way we can improve the design and layout of your webpage with the code you've given us. What I can do is write 'better' readable code.
<?php
function tableCell($content)
{
echo '<td align="left">'.$content.'</td>';
}
// database access
require_once('../mysqli_connect.php');
// get all records from the metabolite table
$response = $db->query("SELECT * FROM metabolite");
// start main division
echo '<div id="main">';
// start the table
echo '<table align="center" cellspacing="2" cellpadding="5" border = "1">';
// walk through all the metabolite records
while ($data = $response->fetch())
{
// start a row
echo '<tr>';
// create the cells
tableCell($data['Metabolite_name']);
tableCell('KEGG: '.$data['Synonyms']);
tableCell($data['Synonyms']);
// finish a row
echo '</tr>';
}
// close the table
echo '</table>';
// close main division
echo '</div>';
// close query
$response->closeCursor();
But this is not worth much, the output should remain the same.
if ($response->num_rows > 0) {
while($data = $response->fetch_assoc()) {
echo "<tr><td>" . $data["Metabolite_name"]. "</td></tr>" . ;
}
}
else {
echo "0 results";
}

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>';
}

I have a record Id that needs to be selected to be updated

I have a simple issue I cannot figure out. I am trying to get the id of the record setup as a link to go to a second page that updates the record. I have the update working when I click on update it takes me to the record. I want the id to do the same.
<html>
<?php
require_once("../db_connect.php");
$stmt = $db->prepare("SELECT * FROM Users");
$stmt->execute();
?>
<?php while( $row = $stmt->fetch(PDO::FETCH_ASSOC) ) { ?>
<table bgcolor=F2F2F2 width=1080 border='2'table-layout: fixed >
<br>
<tr>
<th>Id</th>
<th>Update</th>
<th>First Name</th>
<th>Last name</th>
<th>Address</th>
<th>Bio</th>
</tr>
<tr>
<?php echo "<td>
<a href='../update.php?id=" . $row['id'] . "'>ID</a></td>"?>
<?php echo "<td>
<a href='../update.php?id=" . $row['id'] . "'>Update</a></td>"?>
<td><?php echo $row['First Name']; ?></td>
<td><?php echo $row['Last Name']; ?></td>
<td><?php echo $row['Address']; ?></td>
<td><?php echo $row['Bio']; ?></td>
</tr>
<?php } ?>
</table>
</body>
</html>
In general, it is a good practice to put duplicated content into a function or variable and then call it when needed, to improve code readability & to save time/space.
I have also noticed many people struggling with new syntax so I have split the "one-liners" and left comments explaining how does new syntax works.
function col_gen($slug,$id=''){
return (!empty($id))? // If ID parameter exist and not empty generate column with a link
'<td>'.$slug.'</td>': //else
'<td>'.$slug.'</td>';
}
And then, in your case, you can run this function inside a loop:
....
foreach($row as $k=>$slug){
echo ($k==='id')? //if key equals "id"
col_gen($slug,$slug) // Output column for ID
.col_gen('Update',$slug) // Output column for keyword Update
:col_gen($slug); //else output just column with the slug
/**
* Learn one-line PHP, you will love it, once you understand it...
* Full Example Above:
* echo ($k==='id') ? col_gen($slug,$slug).col_gen('Update',$slug):col_gen($slug);
**/
}

Categories