Display MySQL Results into HTML Table with URL - php

The code below isn't working as intended. I was wanting 3 columns with the first column being a site name, the second column being the category, and the third being the URL for RSS (haven't gotten to that part yet). The data is in the database but when I view the result of the statements below, the site name results link to the current web page I am on. I would greatly appreciate any assistance with getting each column of data to display on the page correctly. Thank you
<?php
$query="SELECT * FROM SOMETABLE";
$result=mysql_query($query);
$num = mysql_numrows($result);
echo "
<table border='1'>
<th>Site Name:</th>
<th>Category:</th>
<th>RSS:</th>";
$i=0;
while ($i < $num) {
$siteName =mysql_result($result,$i,"siteName");
$category =mysql_result($result,$i,"category");
$category =mysql_result($result,$i,"url");
$rss =mysql_result($result,$i,"rss");
echo "
<tr>
<td><a href='$url'>$siteName</a></td>
<td>$category</td>
<td>$rss</td>
</tr>";
$i++;
}
?>

echo "<table>";
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo "<tr>";
echo "<td>$line ["siteName"]</td>";
echo "<td>$line ["category"]</td>";
echo "<td>$line ["url"]</td>";
echo "<td>$line ["rss"]</td>";
echo "</tr>";
}
echo "</table>";
skip $num, mysql_resuls ( the way how you do it ) open row TR in headers ( I skipped it ) and close table

echo "
<table border='1'>
<th>Site Name:</th>
<th>Category:</th>
<th>RSS:</th>";
Should be:
echo "
<table border='1'>
<tr>
<th>Site Name:</th>
<th>Category:</th>
<th>RSS:</th>
</tr>";
To start with.

Or just use some tool like SDTable.com or jqGrid and let them do all job for you =)

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>

How to make usernames display in rows and columns in a Table

I have this table im trying to display users, being 2 users per 2 columns, then list down. Here is what i have so far:
<?php $result = mysql_query("SELECT * from users WHERE adminlevel='5'");
while($row = mysql_fetch_array($result)) { echo
" <table>
<tr>
<td width='85' align='left'><br><center>". $row['username'] . "</center>
</td>
<td align='right'><center></center>
</td>
</tr>
<td width='85' align='left'><center></center>
</td>
<td align='right'><center></center>
</td>
</table>";
} ?>
This just displays the members as rows going down, and missing out the other column completely. I was hoping that it would display the username in each of the table fields. I also did try putting ". $row['username'] ." in the other fields too, but that just duplicated it.
EDIT:
So iv'e changed it to this, I can't see going down as I only have 2 members, Would this work:
<?php $result = mysql_query("SELECT * from users WHERE adminlevel='5'"); ?>
<table>
<tr>
<?php while($row = mysql_fetch_array($result)) { echo
"<td width='85' align='left'><font size='1px'><center>". $row['username'] . "</font></center></td>
<td align='right'><center></center></td>";
} ?>
</tr>
</table>
example:
try something like this
<table>
<tr>
<th>name</th>
<th>name</th>
</tr>
<?php
$result = mysql_query("SELECT * from users WHERE adminlevel='5'");
$i = 0;
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
if ($i == '0') echo "<tr>";
echo "<td>{$row['username']}</td>";
if ($i == '1') echo "</tr>";
$i++;
if($i =='2')$i='0';
}
?>
</table>
I think you're asking why the other fields in your "user" mysql table aren't showing up.
They aren't there because you only asked for the username:
$row['username']
If you have first/last name in your mysql table, you can retrieve it in the same way:
$row['firstname']
$row['lastname']
In your code you got the row as a key/value array like this:
$row = mysql_fetch_array($result)
The "key" is the name of the mysql column, like username, lastname, firstname. And the value is what is stored in the mysql table under that row/column, like joecool, smith, joe.

Why oci_fetch_array($stid) don't return the first row of oracle database table

I'm trying to make a search form that return some data from an oracle database,it works fine except that it skip the first row of table .
I used the following code :
enter code here
if(isset($_POST['search']) && !empty($_POST["search_box"])){
$name=$_POST['search_box'];
$sql='SELECT deejays.name,available_dates.data, available_dates.venue,available_dates.location FROM deejays,available_dates';
$sql .=" WHERE deejays.name ='{$name}'";
$sql .=' AND pk_id=fk_id';
$verify="SELECT deejays.name FROM deejays WHERE deejays.name ='{$name}'";
$stid = oci_parse($conn,$sql );
oci_execute($stid);
if (oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)){
echo "<table width=\"100%\" align=\"center\" cellpadding=\"5\" cellspacing=\"5\">
<tr class=\"source\">
<td colspan=3 align=\"center\"><h1>The facebook tour dates for ".$name." are:</h1></td>
</tr>
<tr align=\"center\" class=\"source1\">
<td><strong>DATA</strong></td>
<td><strong>VENUE</strong></td>
<td><strong>LOCATION</strong></td>
</tr>";?>
<?php while($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)){ ?>
<tr align="center" class="rows">
<td ><?php echo $row['DATA'];?></td>
<td ><?php echo $row['VENUE'];?></td>
<td ><?php echo $row['LOCATION'];?></td>
</tr>
<?php } ?>
</table>
<?php } else {
$stid = oci_parse($conn,$verify );
oci_execute($stid);
if (oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS))
{ echo "This artist hasn't records on facebook/bandsintown<br>
enter code here
the expected result is:
and the real result is:
The second image shows that the first row is skipped,how could I solve this?Thanks in advance
As I commented, oci_fetch_array() will return an array containing the next result-set row of a query. Which means everytime you call it, the cursor will move to the next row. I have two suggestions.
First
Load all the result into an array after oci_execute(). And count the array if it has any row.
oci_execute($stid);
$result = array();
while($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS))
{
$array[] = $row;
}
//check if result is not empty
if (count($result)) {
//the table part here.
}
And when you want to display it in html table, use foreach loop to iterate the array and build the <tr>.
<?php foreach($result as $row) { ?>
<tr align="center" class="rows">
<t ><?php echo $row['DATA'];?></td>
<td><?php echo $row['VENUE'];?></td>
<td><?php echo $row['LOCATION'];?></td>
</tr>
<?php } ?>
SECOND
You can use oci_fetch_all() to load all the rows from the query into an array.
oci_execute($stid);
//$result will have all the result of the current query
$count = oci_fetch_all($stid, $result);
if ($count) {
//table part here
}
And building the <tr> will be the same as the first.
Another way is to use buffered query. But this will depend on many factors.

PHP is there a simpler and tidier way of doing this?

I am trying to create a menu where users can view a menu that they create. The menu consists of a dropdown box which the users use to filter the menu by week.
The menu then displays the seven days of the week and the five types of meal times their are which is breakfast, lunch, dinner, pudding and snack. Below is how i am currentley displaying it so far.
$sqlmeasurement = mysql_query("SELECT title FROM recipe JOIN menu ON recipe.recipeid = menu.recipeid WHERE menu.weekid = '".$selectweek."' AND menu.mealtimeid = '1'") or die(mysql_error());
Print '<table border="0">
<tr>
<th width="100"> </th>
<th width="200">Monday</th>
</tr>';
echo "<tr>";
echo "<td><strong>Breakfast</strong></td>";
echo "<td>";
while($info = mysql_fetch_array( $sqlmeasurement ))
{
echo $info['title'];
echo "<br/>";
}
echo "</td> ";
echo "</tr>";
echo "</table>";
As you can see this PHP statement selects what i want from the table but because there are 7 days a week and 5 types of meal times this means that i will have to copy this code 35 times in order to display all that i want.
So for example the next bit of code will be like this:
$sqlmeasurement2 = mysql_query("SELECT title FROM recipe JOIN menu ON recipe.recipeid = menu.recipeid WHERE menu.weekid = '".$selectweek."' AND menu.mealtimeid = '2'") or die(mysql_error());
Print '<table border="0">';
Print '<tr>
<th width="100"> </th>
<th width="200"> </th>
</tr>';
echo "<tr>";
echo "<td><strong>Lunch</strong></td>";
echo "<td>";
while($info2 = mysql_fetch_array( $sqlmeasurement2 ))
{
echo $info2['title'];
echo "<br/>";
}
echo "</td> ";
echo "</tr>";
echo "</table>";
And so on until i have all the days and their meal times.
Is there a way to display all the information without all this iteration?
You have various options. You could put the output into a function, and just call that with varying parameters.
function ouptutMeal($selectweek, $mealtime, $mealname) {
$sqlmeasurement2 = mysql_query("SELECT ... WHERE menu.weekid = '$selectweek' AND menu.mealtimeid = '$mealtime'");
echo "<table>
<tr>
<th> </th>
<th> </th>
</tr>
<tr>
<td><strong>$mealname</strong></td>
<td>";
while($info2 = mysql_fetch_array( $sqlmeasurement2 )) {
echo $info2['title'], '<br/>';
}
echo '</td>
</tr>
</table>';
}
ouptutMeal($selectweek, 1, 'breakfast');
ouptutMeal($selectweek, 2, 'lunch');
Or you could use a different query to get all the information at once, and loop through it:
$q = "SELECT title, mealtimeid, mealtimename
FROM ...
WHERE menu.weekid = '$selectweek'
ORDER BY menu.mealtimeid";
You can then iterate through the results, assembling them into, say, a 2D array based on using mealtimename as a key. e.g.
$mealInfo = array()
while($info = mysql_fetch_array( $result )) {
$mealInfo[$info['mealtimename'][] = $info;
}
foreach ($mealInfo as $mealName => $mealData) {
ouptutMeal($mealName, $mealData);
}

Categories