I want my users to search my database to return data from two different tables which I have done using UNION but I want it to not only search from two tables but to also display as two tables..How can I go about doing this?
$result .= "<table border='1'>";
$result .="<tr><td>Cater</td><td>Part</td><td>Gids</td></tr>";
while ($row = mysql_fetch_array($sql)){
$result .= '<tr>';
$result .= '<td>'.$row['Name'].'</td>';
$result .= '<td>'.$row['Part'].'</td>';
$result .= '<td>'.$row['Gid'].'</td>';
$result .= '</tr>';
}
$result .= "</table>";
$result .= "<table border='1'>";
$result .="<tr><td>Cater</td><td>Dish</td><td>Gids</td></tr>";
while ($row = mysql_fetch_array($sql)){
$result .= '<tr>';
$result .= '<td>'.$row['Name'].'</td>';
$result .= '<td>'.$row['Dish'].'</td>';
$result .= '<td>'.$row['Gid'].'</td>';
$result .= '</tr>';
}
$result .= "</table>";
If you're going to do it this way, you need some way to tell where the first results end and the second start. An easy way is to add an extra column in the result set:
Select
0 as resultset,
Name,
Part,
Gid
From
Parts
Union All
1,
Name,
Dish,
Gid
From
Dishes
Order By
resultset -- I'm not sure if you need this, or whether you get it for free
Then you need to break out of the first loop if you've moved to the second result set. Also, the column names in the union will all reflect the first part, so I've changed Dish to Part. You also have to deal with the possibility that either or both of the parts of the union may return nothing.
$result .= "<table border='1'>";
$result .="<tr><td>Cater</td><td>Part</td><td>Gids</td></tr>";
while ($row = mysql_fetch_assoc($sql) && $row['resultset'] === 0) {
$result .= '<tr>';
$result .= '<td>'.$row['Name'].'</td>';
$result .= '<td>'.$row['Part'].'</td>';
$result .= '<td>'.$row['Gid'].'</td>';
$result .= '</tr>';
}
$result .= "</table>";
$result .= "<table border='1'>";
$result .="<tr><td>Cater</td><td>Dish</td><td>Gids</td></tr>";
while ($row){
$result .= '<tr>';
$result .= '<td>'.$row['Name'].'</td>';
$result .= '<td>'.$row['Part'].'</td>';
$result .= '<td>'.$row['Gid'].'</td>';
$result .= '</tr>';
$row = mysql_fetch_assoc($sql);
}
$result .= "</table>";
Your probably do have two tables but right next to each other. Try putting something visble in between. I put an HR but you can put what makes sense visually for your page. Even a BR ot table header text would work.
$result .= "<table border='1'>";
$result .="<tr><td>Cater</td><td>Part</td><td>Gids</td></tr>";
while ($row = mysql_fetch_array($sql)){
$result .= '<tr>';
$result .= '<td>'.$row['Name'].'</td>';
$result .= '<td>'.$row['Part'].'</td>';
$result .= '<td>'.$row['Gid'].'</td>';
$result .= '</tr>';
}
$result .= "</table>";
$result .= "<hr />"; <=========
$result .= "<table border='1'>";
$result .="<tr><td>Cater</td><td>Dish</td><td>Gids</td></tr>";
while ($row = mysql_fetch_array($sql)){
$result .= '<tr>';
$result .= '<td>'.$row['Name'].'</td>';
$result .= '<td>'.$row['Dish'].'</td>';
$result .= '<td>'.$row['Gid'].'</td>';
$result .= '</tr>';
}
$result .= "</table>";
Related
I'm trying to dump my MYSQL table via PHP onto my HTML page and I'm having some issues that I've hit a bump on.
Currently I have (Using Bootstrap 4):
require('db.php');
$sql = "SELECT * FROM `users`;";
$table = "";
$result = mysqli_query($connection, $sql) or die(mysql_error());
$table = "<table class='table table-hover table-dark'>";
$table .= "<thread>";
$table .= "<tr>";
$fieldsInfo = $result->fetch_fields();
foreach($fieldsInfo as $fieldinfo)
$table .= "<th scope='col'>{$fieldinfo->name}</th>";
$table .= "</tr>";
$table .= "</thead>";
$table .= "<tbody>";
while ($row = $result->fetch_assoc()) {
$table .= "<tr>";
foreach ($row as $columnValue) {
$table .= "<td>$columnValue</td>";
}
$table .= "</tr>";
$table .= "</tbody>";
$table .= "</table>";
}
echo $table;
?>
And my result looks like so:
Table Display
I believe it's where I'm placing the <tr> and </tr> values in my code, but I've tried placing them both inside and out side of my loops. When placed inside of my loop my table returns all my column values into the first table heading. I further inspected my code via Firefox 'inspect element' and I saw that the second row from the table is actually outside the scope of <table> which makes no sense to me because my loop is obviously before I use </table>.
Hopefully someone can shed some light on this for me, I'm just starting to use PHP so I'm not great with it; but I want to learn.
Your <tr> and </tr> tags look fine where they are. The problem is that the closing </tbody> and </table> tags are inside the while loop. Move them down and it should come out right.
while ($row = $result->fetch_assoc()) {
$table .= "<tr>";
foreach ($row as $columnValue) {
$table .= "<td>$columnValue</td>";
}
$table .= "</tr>";
}
$table .= "</tbody>";
$table .= "</table>";
echo $table;
Use this code :
while ($row = $result->fetch_assoc()) {
$table .= "<tr>";
foreach ($row as $columnValue) {
$table .= "<td>$columnValue</td>";
}
$table .= "</tr>";
}
$table .= "</tbody>";
$table .= "</table>";
This question already has answers here:
How can I loop through a MySQL result set more than once using the mysql_* functions?
(7 answers)
Closed 7 years ago.
I've been working on a project that prints sql data into a table. Recently, I've come into a problem with the table. What this code should do is output a table of results from a MySQL query but all it's outputting is something like:
Item1 Item1
For some reason it leaves all the other fields blank. Here's my code:
$table = "<table class='TestTable'><tr class='tr'>";
while($row = mysql_fetch_assoc($result)){
$table .= "<th class='th'>";
$table .= $row['NameOfItem'];
$table .= "</th>";
}
$table .= "</tr><tr class='tr'>";
while ($row = mysql_fetch_assoc($result)){
$table .= "
<td class='td'>Minimum Bid: <b>";
$table .= $row['MinBid'];
$table .= "</b></td>";
}
$table .= "</tr><tr class='tr'>";
while ($row = mysql_fetch_assoc($result)){
$table .= "<td class='td'>Current Bid: <b>";
$table .= $row['CurrentBid'];
$table .= "</b></td>";
}
$table .= "</tr><tr class='tr'>";
while ($row = mysql_fetch_assoc($result)){
$table .= "<td class='td'>Sold By: <b>";
$table .= $row['SoldBy'];
$table .= "</b></td>";
}
$table .= "</tr><tr class='tr'>";
while ($row = mysql_fetch_assoc($result)){
$table .= "<td class='td'>Time Left: <b>";
$table .= printf('%d days, %d hours, %d minutes left', $diff->d, $diff->h, $diff->i);
$table .= "</b></td>";
}
$table .= "</tr></table>";
echo $table;
When I view source I get:
<table class='TestTable'>
<tr class='tr'>
<th class='th'>Item1</th>
<th class='th'>Item1</th>
</tr>
<tr class='tr'></tr>
<tr class='tr'></tr>
<tr class='tr'></tr>
<tr class='tr'></tr>
</table>
After while($row = mysql_fetch_assoc($result)) {...} you have reached the end of your result set. You have to rewind the result pointer to the beginning of the result set if you want to read it again. Do this by using
while($row = mysql_fetch_assoc($result)){ ... }
mysql_data_seek($result, 0); // Rewind result pointer
while($row = mysql_fetch_assoc($result)){ ... }
mysql_data_seek($result, 0); // Rewind result pointer
while($row = mysql_fetch_assoc($result)){ ... }
First get your results and safe them in an array:
while($r = mysql_fetch_assoc($result)){
$row[] = $r;
}
Then reuse the array as often as needed to build the table like this:
$table .= "</tr><tr class='tr'>";
foreach ($row as $r){
$table .= "
<td class='td'>Minimum Bid: <b>";
$table .= $r['MinBid'];
$table .= "</b></td>";
}
... and yes, mysql-functions are deprecated. When you move to PHP7 they'll be gone. Use PDO or mysqli instead.
I just wrote simple PHP code that would print some of these rows
That's how does my table structure looks like:
That's my PHP code:
$user = mysql_query("SELECT usr FROM ava_members");
$id = mysql_query("SELECT id FROM ava_members");
$email = mysql_query("SELECT email FROM ava_members");
$dt = mysql_query("SELECT dt FROM ava_members");
//$result = mysql_query("SELECT id,email,dt,regIP FROM ava_members ORDER BY dt LIMIT 5");
$final = "";
$final .= "<table border='1'><tr>";
/* TABELA */
$final .= "<td>Nick</td>";
$final .= "<td>ID</td>";
$final .= "<td>Email</td>";
$final .= "<td>Data</td>";
//$final .= "</tr>\n";
/* TABELA */
//user
while($row = mysql_fetch_row($user))
{
$final .= "<tr>";
foreach($row as $cell)
$final .= "<td>$cell <a href=\"\?usrdel=$cell\"\>[DELETE]</a></td>";
$final .= "</tr>\n";
}
//ID
while($row = mysql_fetch_row($id))
{
$final .= "<tr>";
foreach($row as $cell)
$final .= "<td>$cell</td>";
$final .= "</tr>\n";
}
//email
while($row = mysql_fetch_row($email))
{
$final .= "<tr>";
foreach($row as $cell)
$final .= "<td>$cell</td>";
$final .= "</tr>\n";
}
//dt
while($row = mysql_fetch_row($dt))
{
$final .= "<tr>";
foreach($row as $cell)
$final .= "<td>$cell</td>";
$final .= "</tr>\n";
}
mysql_free_result($user);
mysql_free_result($id);
mysql_free_result($email);
mysql_free_result($dt);
echo '<center>' . $final . '</center>';
And there's output:
But as you can guess that's not what I want...
Output that I want should look like this:
It's pretty simple - just learn in2 html tables
You should learn SQL:
$data = mysql_query("SELECT usr, id, email, dt FROM ava_members");
while ($row = mysql_fetch_row($data))
{
$final .= "<tr>";
foreach($row AS $k => $cell) {
$final .= '<td>' . htmlspecialchars($cell);
if ($k == 'usr') {
$final .= '<td>[DELETE]';
}
$final .= '</td>';
}
$final .= "</tr>\n";
}
And yes, do not use mysql_. Use mysqli_ instead.
Here's a function that I wrote to display the data from a MySQL database as an HTML table:
/* Returns all of the results from a query in one nice table */
/* Example usage: echo $db->allResults("taxi0", "time, latitude, longitude",40,50); */
function allResults($table,$cols,$limstart,$lim) {
if(isset($cols)) {
$query = "SELECT $cols FROM $table LIMIT $limstart,$lim";
}
else {
$query = "SELECT * FROM $table LIMIT $limstart,$lim";
}
$result = $this->query($query);
$output = '<table class="allResults">';
$data = array();
while($row = $this->fetchAssoc($result)) {
$data[] = $row;
}
$colNames = array_keys(reset($data));
$output .= "<tr>";
foreach($colNames as $colName) {
$output .= "<th>$colName</th>";
}
$output .= "</tr>";
foreach($data as $row) {
$output .= "<tr>";
foreach($colNames as $colName) {
$output .= "<td>".$row[$colName]."</td>";
}
$output .= "</tr>";
}
$output .= '</table>';
return $output;
}
Hope it will help you out.
PDO example, as it is both not deprecated and more fun:
// precondition: $row should be a numbered array of column data
function table_row_from_db_row($row) {
$result = '';
foreach($row as $key => $value) {
$result .= "<td>$value</td>\n";
}
return "<tr>\n$result</tr>\n";
}
// precondition: $headers should be an associative array representing the
// first row
function table_head_from_first_row($row) {
$result = '';
foreach($row as $name => $unused) {
$result .= "<th>$name</th>\n";
}
return "<tr>\n$result</tr>\n";
}
// precondition: $sth is a PDO statement handle from a query that returns
// more than 0 rows.
// postcondition: if there were no rows, returns NULL. Otherwise returns
// an HTML table as a string.
function table_from_query_handle($sth) {
$result = '';
// Fetch the first row so we can get column header names.
$row = $sth->fetch(PDO::FETCH_ASSOC);
if(!$row) {
return NULL;
}
$result .= table_head_from_first_row($row);
do {
$result .= table_row_from_db_row($row);
}
while($row = $sth->fetch(PDO::FETCH_ASSOC));
return "<table>\n$result</table>\n";
}
// Alias the column names to the table headers we want to use on the page.
// If we wanted to build the table manually it would still help that we don't
// have two different names for each field (e.g. `dt` and `data`).
$query = "select usr Nick, id ID, email Email, dt Data from ava_members";
// Connect to the database. This belongs in another file in production code.
$dbh = new PDO('mysql:host=localhost;dbname=test');
// Execute the query and get a statement handle.
$sth = $dbh->query($query);
echo table_from_query_handle($sth);
I have a table with 4 values, 3 of which I am interested in. The MYSQL query I am using is:
Select Product.product_id, Product.cost, Product.image from Product
I have tested this query and it works with my database. I can figure out how to get single columns to return values, but I cannot figure out multiple columns. I have tried a variety of for loops, using an array to store the various column names and iterating things. I'm getting very frustrated, and am not sure what to do.
This was my last attempt:
$conn = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME) or
die('There was a problem connecting to the database');
$stmt = "Select Product.product_id, Product.cost, Product.image from Product";
if(!$result = $conn->query($stmt)){
die('there was an error retrieving the information');
}
$tablebuild = "<table>";
while ( $row = $result->fetch_assoc() ){
foreach ($row as $next){
$tablebuild .= "<tr><td>";
$tablebuild .= $result['product_id'];
$tablebuild .= "</td><td>";
$tablebuild .= $result['cost'];
$tablebuild .= "</td><td>";
$tablebuild .= $result['image'];
$tablebuild .= "</td></tr>";
}
$tablebuild .= "</table>";
Obviously I'm trying to build it into a string of code so I can echo it later into the page where I need it. Every time I run this page, though, I get nothing but a blank page with no source code.
Lose the foreach and use $row, not $result
while ( $row = $result->fetch_assoc() ){
$tablebuild .= "<tr><td>";
$tablebuild .= $row['product_id'];
$tablebuild .= "</td><td>";
$tablebuild .= $row['cost'];
$tablebuild .= "</td><td>";
$tablebuild .= $row['image'];
$tablebuild .= "</td></tr>";
}
I think your problem is that you dont close your while loop ,also your foreach is not correct ,this is how it should be even if it's not necessary :
$tablebuild .= "<table>";
while ( $row = $result->fetch_assoc() ){
$tablebuild .= "<tr>";
foreach ($row as $next){
$tablebuild .= "<td>$next<td>";
}
$tablebuild .= "</tr>";
}
$tablebuild .= "</table>";
The reason this is complicated (for me) is that each column of the table is loaded from a separate MySQL table, and each MySQL table will have varying number of records. Initially I thought I could start generating the html table from top-left to bottom-right column by column , cell by cell, but this won't work because each MySQL table will have different length of records, which generate malformed html tables. Do you have any suggestions?
My idea so far:
Get a list of all tables in MySQL, which determine the number of
columns
Get the count from the table with most records
Create a table with the parameters (# of tables as columns, max# as rows
Update each cell with the corresponding record, but not quite sure how
As requested, some code:
$tables = mysql_query("show tables");
$output = "<table border=1><thead><tr>";
while($table = mysql_fetch_array($tables)) {
$output .= "<td>";
$output .= $table[0];
$output .= "</td>";
$tableNames[] = $table[0];
}
$output .= "</tr></thead>";
$output .= "<tbody>";
//Get a count of the table with the most records
for($i=0; $i<count($tableNames); $i++ ){
$currentTable = $tableNames[$i];
$tableContent = mysql_query("select * from $currentTable") or die("Error: ".mysql_error());
//Generating all content for a column
$output .= "<tr>";
while($content = mysql_fetch_array($tableContent)){
//generating a cell in the column
$output .= "<td>";
$output .= "<strong>".$content['subtheme'].": </strong>";
$output .= $content['content'];
$output .= "</td>";
}
$output .= "</tr>";
}
$output .= "</tbody>";
$output .= "</table>";
This is wrong not just because it generates a malformed table, but also because it transposed columns to rows...
Any help would be appreciated
Solution to my much hated question:
$mymax = 0;
for($i=0; $i<count($tableNames); $i++){
$currentTable = $tableNames[$i];
$tableCounts = "select * from $currentTable";
if($stmt = $mysqli->prepare($tableCounts)){
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
$count = mysqli_stmt_num_rows($stmt);
mysqli_stmt_close($stmt);
}
($mymax >= $count ? "" : $mymax = $count);
$colWidth = 100 / count($tableNames);
}
// DIV GRID
// via DIV GENERATION
$output .= "<div class='grid'>";
for ($i=0; $i<count($tableNames); $i++){
$output .= "<div id='col$i' class='col' style=\"width:$colWidth%\">";
$output .= "<h3>".$tableNames[$i]."</h3>";
$tableqry = "select * from $tableNames[$i]";
if ($result = mysqli_query($mysqli, $tableqry)) {
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
$output .= "<div class='item'>".$row["content"]."</div>";
}
mysqli_free_result($result);
}
$output .= "</div>";
}
$output .="</div>";
$output .="<div class='clear'></div>";