I'm trying to place the output of this PHP SQL query into a database table, but it is outputting all of the row data into one column.
if(isset($_POST['submit'])) {
$name = htmlentities($_POST['name']);
$parts = explode(" ", $name);
$lastname = array_pop($parts);
$firstname = implode(" ", $parts);
$connection = mysql_connect("localhost", "user", "password");
mysql_select_db("shoretoshore", $connection);
$result = mysql_query("SELECT ship_no, shipment_id, arrival_date, origin, destination, lname, fname from shipment, captain WHERE captain.capt_id=shipment.capt_id AND captain.fname='$firstname' AND captain.lname='$lastname'", $connection);
echo '<table border="0" cellpadding="5px" cellspacing="1px" style="font-family:Verdana, Geneva, sans-serif; font-size:11px; background-color:#E1E1E1" width="100%">
<tr bgcolor="#FFFFFF" style="font-weight:bold">
<th>Shipment No.</th>
<th>Shipment Id.</th>
<th>Arrival Date</th>
<th>Origin</th>
<th>Destination</th>
<th>Last Name</th>
<th>First Name</th>
</tr>';
while ($row = mysql_fetch_row($result)) {
foreach ($row as $value)
print "<tr><td>"."{$value}"."</td></tr>";
echo "<br>";
}
echo "</table>";
}
How do I output the results of the query into an HTML table?
You are putting the $value inside quotation marks, it will be treated as string.
Try:
while ($row = mysql_fetch_row($result)) {
echo '<tr>';
foreach ($row as $value)
{
echo "<td>".$value."</td>";
}
echo "</tr>";
}
You need to explain the issue you're having. But from what I can see off the bat, you're looping through all the values of the row and outputting them as rows itself, instead of as a cell within the table row. The curly brackets around value are unnecessary as well, since you are concatenating the strings, you can just do '<tr><td>'.$value.'</td></tr>' OR "<tr><td>$value</td></tr>". PHP will parse variables within a string if the string is double quoted. I would also refrain from adding <br> tags as direct children of a table. If you need spacing between table rows, use padding and margins.
try this
while ($row = mysql_fetch_row($result)) {
print "<tr><td>".$row[0]."</td></tr>";
echo "<br>";
}
The problem is that you're outputting a <tr> tag for every row and column. You need to move the <tr> outside the inner loop.
Technically, you don't need to concatenate "{$value}" with the other two strings, but you really should pass $value through htmlspecialchars() to avoid producing incorrect HTML if the value contains any < or & characters. Eg:
while ($row = mysql_fetch_row($result)) {
print '<tr>';
foreach ($row as $value) {
$v = htmlspecialchars ($value);
print "<td>$v</td>";
}
echo "</tr>\n";
}
Also, you're not supposed to have a <br> element between table rows, which is why I replaced it with a newline above. Personally, I would skip the closing </td> and </tr> tags since they are optional in HTML.
Note also, that the MySQL extension is deprecated and no longer maintained. You should be using MySQLi or PDO these days.
while ($row = mysql_fetch_row($result)) {
echo '<tr>';
foreach ($row as $value)
{
echo "<td>".$value."</td>";
}
echo "</tr>";
}
Related
I'm creating a webpage that lists ten characters in a game based on their experience levels and displays them with a picture associated each character. My code works, but the output is in a column when I'd like it to be in a row. I did see where something very similar had been asked here: MySQL data from database align horizontally and I tried to follow that example but either ended up with errors or the faces didn't appear. I'm a hobbyist, I'm just doing this for friends, so my knowledge is pretty basic.
Relevant code:
<table border="3" width="90%">
<tr>
<th width="25%">XP</th>
<td>
<?php
$resultgood = mysqli_query($con,"SELECT * FROM Life WHERE goodxp > 0 ORDER BY goodxp DESC LIMIT 10");
while($row = mysqli_fetch_array($resultgood))
{
$face = mysqli_query($con,"SELECT face FROM Description WHERE charname='$row[charname]'");
$row = mysqli_fetch_row($face);
$face = $row[0];
$name = mysqli_query($con,"SELECT charname FROM Life WHERE charname='$row[charname]'");
$row = mysqli_fetch_row($name);
$name = $row[0];
echo "<left>";
echo "<table border='1'>";
echo "<tr><td>";
echo "<img src='pictures/$face' alt='$name' border='2'>";
echo "</td></tr>";
echo "</table>";
echo "<br>";
}
?>
</td>
</tr>
</table>
Anyone got any suggestions? Thanks!
So after following Bombelman's suggestion below, I got it to work. In case anyone else runs into this problem, here is the working code:
<tr>
<th width="25%">Goody Two Shoes</th>
<td><?php
echo "<table border='1'><tr>";
echo "<left>";
$resultgood = mysqli_query($con,"SELECT * FROM Life WHERE goodxp > 0 ORDER BY goodxp DESC LIMIT 10");
while($row = mysqli_fetch_array($resultgood))
{
$face = mysqli_query($con,"SELECT face FROM Description WHERE charname='$row[charname]'");
$row = mysqli_fetch_row($face);
$face = $row[0];
$name = mysqli_query($con,"SELECT charname FROM Life WHERE charname='$row[charname]'");
$row = mysqli_fetch_row($name);
$name = $row[0];
echo "<td>";
echo "<img src='pictures/$face' alt='$name' border='2'>";
echo "</td>";
}
echo "</tr>";
echo "</table>";
?></td>
</tr>
place the "table" and "row" tag out of the loop, and have the results in between the "td" tags looped only.
Looking at your script, you have several tables.
Make sure only the < td > and < /td > tags are within the while-loop.
The output should be similar to my example.
Hope it helps !
<table style="width:100%">
<tr>
<td>Character 1</td>
<td>Character 2</td>
<td>Character 3</td>
<td>Character 4</td>
<td>Character 5</td>
</tr>
</table>
Looking at the sql queries makes me think you ought to be able to do a basic join upon the two tables rather than having nested queries within a loop. The generation of the html table should be fairly straightforward - iterate through the recordset results for rows in the table and iterate through the fields returned by the query for individual cells within the table row.
$sql='select l.*, d.face from `life` l
join `description` d on d.`charname`=l.`charname`
where l.`goodxp` > 0
order by l.`goodxp` desc
limit 10';
$res=$con->query( $sql );
/* fetch the column names into an array */
$fields=array();
array_walk( $res->fetch_fields(),function( $item, $key, $fields ){
$fields[]=$item->name;
},&$fields );
$html=array();
$html[]='<table>';
/* add field names as column headers */
$html[]='<tr>';
foreach( $fields as $field )$html[]='<th>'.$field.'</th>';
$html[]='</tr>';
/*
iterate through recordset,
add new row for every record
but table cell for every
field in record
*/
while( $rs=$res->fetch_object() ){
$html[]='<tr>';
foreach( $fields as $field ){/* show image or text */
$data = $field=='face' ? "<img src='pictures/{$rs->$field}' />" : $rs->$field;
$html[]='<td>'.$data.'</td>';
}
$html[]='</tr>';
}
$html[]='</table>';
/* render table */
echo implode( PHP_EOL, $html );
Depending upon the version of PHP you may get nagged at when using the array_walk function and passing the third argument by reference. If that is the case then change
$fields=array();
array_walk( $res->fetch_fields(),function( $item, $key, $fields ){
$fields[]=$item->name;
},&$fields );
for
$fields=array();
array_walk( $res->fetch_fields(),function( $item, $key ){
global $fields;
$fields[]=$item->name;
} );
Hi so im trying to put all of the useres in a database, table into a html table this is what i have:
<table class="table table-striped">
<thead>
<tr>
<th>UUID</th>
<th>Full Name</th>
<th>Email</th>
<th>Access Key</th>
<th>Phone Number</th>
<th>Activated</th>
<th>Role</th>
</tr>
</thead>
<tbody>
<?php
include_once('inc/conf/databaseConnect.php');
$query = mysql_query("SELECT * FROM list_users ORDER by id");
while($row = mysql_fetch_array($query)){
echo "<tr>";
echo "<td>".$row['uuid']."</td>";
echo "<td>".$row['firstname'].$rowtwo['lastname']."</td>";
echo "<td>".$row['email']."</td>";
echo "<td>".$row['security_key']."</td>";
echo "<td>".$row['phone_no']."</td>";
echo "<td>".$row['activated']."</td>";
echo "<td>".$row['role']."</td>";
echo "</tr>";
}
?>
</tbody>
</table>
This dosnt return anything, or any errors. It connects to the database correctly ive checked that its just not retrieving the users.
Image of database structure
databaseConnect.php:
<?php
//Create Connnection
$sqlLink = mysqli_connect('localhost', 'root', 'classified', 'user_details');
//If Error Connecting
if(!$sqlLink) {
die('<center><br><h3>Error connecting to servers Database.');
}
?>
After seeing your edit because you did not originally show us which connection method you were using; the almighty answer here (least the most important one) is that you can't mix different MySQL APIs.
Can I mix MySQL APIs in PHP?
You need to use the same one from connection to query.
Plus that $rowtwo should be $row as I stated in comments along with my asking about what was inside your databaseConnect.php file.
Get to work with prepared statements also to help protect against an SQL injection.
https://en.wikipedia.org/wiki/Prepared_statement
Thanks. I have fixed the issue i updated to using mysqli's methods
<?php
include_once('inc/conf/databaseConnect.php');
$query = $sqlLink->query("SELECT * FROM list_users ORDER by id");
while($row = $query->fetch_array()){
echo "<tr>";
echo "<td>".$row['uuid']."</td>";
echo "<td>".$row['firstname'].$row['lastname']."</td>";
echo "<td>".$row['email']."</td>";
echo "<td>".$row['security_key']."</td>";
echo "<td>".$row['phone_no']."</td>";
echo "<td>".$row['activated']."</td>";
echo "<td>".$row['role']."</td>";
echo "</tr>";
}
?>
At least check for errors:
if ($query = mysql_query("SELECT * FROM list_users ORDER by id");) {
...
} else {
echo '<b>MySQL error:</b><br>' . mysql_error() . '<br />';
}
You must use mysql_fetch_assoc() instead of mysql_fetch_array or fetch like this mysql_fetch_array($result, MYSQL_ASSOC).
I'm just struggling to have my SQL output loop within a table. Currently, it displays one result within the table and the remaining out of it.
If I put the entire table within the while loop, it creates a new table for each row...
Please help!
Code below
if (mysqli_num_rows($result) > 0)
{
echo
"<table class='xsmall' align='center'>
<tr><th>Costume ID</th>
<th>Description</th>
<th>Size</th></tr>";
while($row = mysqli_fetch_array($result))
{
//-----------------Echoing Results-----------------------//
echo
"<tr><td>".$row['Fname']."</td>
<td>".$row['Sname']."</td>
<td>".$row['AvgSpend']."</td></tr>
</table><br>";
}
}
echo "<table>";
while($row = mysqli_fetch_array($result)) {
echo "
<tr>
<td>'".$row['Fname']."'</td>
<td>'".$row['Sname']."'</td>
<td>'".$row['AvgSpend']."'</td>
</tr>";
}
echo "</table>";
I want to show the query results of mysql query in a table,
There are two tables, and some information has to be retrieved from the second table
I want to retrieve title, borrower name and borrower surname from other tables,
I tried to retrieve title, but I was unsuccessful,
Then I want to retrieve the borrower name and borrower surname from the users table
You may also offer a new way to put the results into a table
Here is the code
for($i=0;$i<999999999;$i++){
$sql="SELECT * FROM products WHERE product_id='$i' LIMIT 1";
//echo $sql;
$moviename="SELECT dbid FROM products WHERE product_id='$i'";
$dbid=mysql_query($moviename);
$movname="SELECT title FROM titles WHERE dbid='$dbid' ";
$name=mysql_query($movname);
$title=mysql_fetch_array($name);
print "<table border=1>
<tr><th>Product_ID</th>
<th>dbid</th>
<th>Title</th>
<th>Status</th>
<th>Date</th>
<th>Borrowe_id</th>
<th>Borrower Name</th>
<th>Borrower Surname</th></tr>";
$result=mysql_query($sql);
if($result==NULL){
continue ;
}
while ($row = mysql_fetch_array($result))
{
print "<tr><td>{$row[1]}</td>
<td>{$row[2]}</td>
<td>{$title[0]}</td>
<td>{$row[12]}</td>
<td>{$row[13]}</td>
<td>{$row[14]}</td>
<td>{$borrowername[0]}</td>
<td>{$borrowesurname[0]}</td></tr>";
}
print "</table>";
}
?>
There are a few things going on here which you should definitely not be doing.
Super insane loop with a query inside
for($i=0;$i<999999999;$i++){
// SELECT STATEMENT HERE!
}
Why are you looping potentially 999,999,999 times? And if you do you are going to hit your database 999,999,999 times? That is going to kill your database and it can be done much more efficiently.
Use joins over individual selects
$sql="SELECT * FROM products WHERE product_id='$i' LIMIT 1";
$moviename="SELECT dbid FROM products WHERE product_id='$i'";
$movname="SELECT title FROM titles WHERE dbid='$dbid' ";
Note:
product_id='$i' LIMIT 1
Usually you want your ids to be unique. Why do you need to LIMIT your query?
The query can be simplified to:
select
*
from
products p
left outer join titles t
on p.dbid = t.dbid
Note: SELECTING * IS BAD PRACTICE, BUT I DON'T KNOW WHAT YOUR STRUCT IS
Illogical logic
if($result==NULL){
continue ;
}
while ($row = mysql_fetch_array($result)) {...}
$result is null at this point, so your while loop will never happen.
So after killing that loop, simplifying the query, and revising logic... we can do:
$result_resource = mysql_query($sql);
echo"
<table border=1>
<tr>
<th>Product_ID</th>
<th>dbid</th>
<th> Title</th>
<th>Status</th>
<th>Date</th>
<th>Borrowe_id</th>
<th>Borrower Name</th>
<th>Borrower Surname</th>
</tr>";
while ($row = mysql_fetch_array($result_resource))
{
echo "
<tr>
<td>{$row['ProductID']}</td>
<td>{$row['dbid']}</td>
<td>{$row['Title']}</td>
<td>{$row['Status']}</td>
<td>{$row['Date']}</td>
<td>{$row['Borrowe_id']}</td>
<td>{$borrowername[0]}</td>
<td>{$borrowesurname[0]}</td>
</tr>";
}
echo "</table>";
Looking at $borrower.... I have a feeling you can also join your borrow table to the query to bring that in too.
I would also look into templating. It would definitely separate your data from your display and make your code a lot easier to read.
First,you should debug your code
one thing that pops up is the following error:
you should change the following from:
print "<tr><td>{$row[1]}</td>
<td>{$row[2]}</td> ..."
to:
print "<tr><td>{" . $row[1] . "}</td>
<td>{" . $row[2] . "}</td> ..."
Second, when you say " I was unsuccessful" - please add details, did you get an error ? what was the output ?
(Maybe your question is "too localize")
First I don't recommend this :
for($i=0;$i<999999999;$i++)
because it will take long for the server to compute, and generate a lot of mysql query.
Second, most (all?) of your mysql queries could be merge in only one query.
You can about query on more then one table here (dev.mysql.com) There's several way to join multiples tables, you could read about it
Third, in your code the table header will be repeated each time, because it's in your For loop.
here my suggest to improve your code :
//Print the header
print "<table border=1>
<tr><th>Product_ID</th>
<th>dbid</th>
<th>Title</th>
<th>Status</th>
<th>Date</th>
<th>Borrowe_id</th>
<th>Borrower Name</th>
<th>Borrower Surname</th></tr>";
//adapt the following sql with your tables name / fields
$sql="SELECT products.product_id, products.dbid, title.tiles, product.status, product.date, borrow.id , borrow.name, borrow.surname FROM products,titles,borrow WHERE product.dbid = titles.dbid && borrow.id = product.prodict_id LIMIT 1";
$result=mysql_query($sql);
while ($row = mysql_fetch_array($result))
{
print "<tr><td>{$row[1]}</td>
<td>{$row[2]}</td>
<td>{$row[3]}</td>
<td>{$row[4]}</td>
<td>{$row[5]}</td>
<td>{$row[6]}</td>
<td>{$row[7]}</td>
<td>{$row[8]}</td></tr>";
}
print "</table>";
?>
I know that the sql query isn't the best one, but I think those suggestions could help you.
Here is a function for you to convert any MySQL select statement to a HTML table with table headings.
function createTable_from_sql_select_query($query) {
$sql_link = Connect_MySQLi_DB(); // Your Database Connection
$sql_link->set_charset("utf8");
$result = $sql_link->query($query);
// Adding Missing Array Column Function for Old PHP Versions (<5.5)
if (!function_exists('array_column')) {
function array_column($array, $column) {
$ret = array();
foreach ($array as $row)
$ret[] = $row[$column];
return $ret;
}
}
$headings = json_decode(json_encode($result->fetch_fields()), true);
$headings = array_column($headings, 'name');
$return = '<table>';
$return .= '<thead><tr>';
for ($x = 0; $x <= (count($headings) - 1); $x++) {
$return .= '<th>' . ucwords(str_replace('_', ' ', (strtolower($headings[$x])))) . '</th>';
}
$return .= '</tr></thead><tbody>';
while ($row = $result->fetch_object()) {
$return .= '<tr>';
for ($x = 0; $x <= (count($headings) - 1); $x++) {
$return .= '<td>' . $row->$headings[$x] . '</td>';
}
$return .= '</tr>';
}
$return .= '</tbody></table>';
return $return;
}
Below is my code:
while ($row = mysql_fetch_array($result)) {
echo "
<tr>
<td>{$row['TeacherForename'].$row['TeacherSurname']}</td>
<td>{$row['StudentForename'].$row['StudentSurname']}</td>
</tr>";
}
I want TeacherForname and TeacherSurname to concatenate with each other and StudentForename and StudentSurname and when I researched it says use the . syntax to concatenate but it doesn't work.
How are you suppose to do it?
while ($row = mysql_fetch_array($result)) {
echo "
<tr>
<td>{$row['TeacherForename']}{$row['TeacherSurname']}</td>
<td>{$row['StudentForename']}{$row['StudentSurname']}</td>
</tr>";
}
As long as you do that in the string context - . cannot be treated as php concatenation operator. So just place two variables together and that's it.