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);
Related
I was wondering if anyone could help with a conceptual issue I'm having, or if there is a better way.
Basically I am searching my database for an array of terms through a search bar.
I have a function that loops through each term and then uses that for a search. It puts everything in an array and returns the array that is then processed into a table.
The search works fine, I put in the terms and it loops through them pushing the rows into an array. Now because I am pushing into different Arrays, the parent Array I Have has indexed keys, I want to change that to be keys of the terms and in the array there are two other arrays 1 for the number of results and another for the results.
// Search index php
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
</head>
<body>
<div id="search">
<form id= "search" action="searchresults.php" method="POST">
<input type="text" name="txtsearch" size="30" id="txtsearch">
<input type="submit" name="srchbtn" id="srchbtn">Search</button>
</form>
</body>
</html>
//Search PHP
<?php
include_once "iud.php";
$arrayval = array();
if(isset($_POST['txtsearch'])){
$search=$_POST['txtsearch'];
}else{
$search = '';
}
$search1 = explode(" ", $search);
array_push($arrayval, $search1);
$combined = array();
foreach ($arrayval as $val){
$orIndex = checkOr($val);
if(empty($orIndex)){
$valcntr = count($val);
$results = getResults($val);
print_r($results);
}
}
function getResults($array){
include_once "iud.php";
$db = connectDatabase();
$totalResults = array();
$length = count($array);
for ($i = 0; $i < $length; $i++){
$outputDisplay = "";
$myrowcount = 0;
$sql_statement = "SELECT userid, username, firstname, lastname ";
//, congroup, cattype, company, position, email, website, phone, mphone, wphone, fax, add1, add2, city, state, zip, country, reference, entrydate, enteredby, notes ";
$sql_statement .= "FROM userlist ";
$sql_statement .= "WHERE (firstname LIKE '%$array[$i]%' or lastname LIKE '%$array[$i]%')";
$sql_statement .= "ORDER BY lastname, firstname";
$sqlResults = selectResults($db, $sql_statement);
$error_or_rows = $sqlResults['resultNum'];
if (substr($error_or_rows, 0 , 5) == 'ERROR')
{
$outputDisplay .= "<br />Error on DB";
$outputDisplay .= $error_or_rows;
} else {
array_push($totalResults, $sqlResults);
$arraySize = $error_or_rows;
}
}
return ($totalResults);
}
function buildTable($totalResults){
include_once "iud.php";
$outputDisplay = "";
$outputDisplay .= '<div id="resultstable">';
$outputDisplay .= '<ul id="results">';
$myrowcount = 0;
for ($i=0; $i < count($totalResults); $i++)
{
$myrowcount++;
$contactid = $totalResults[$i]['userid'];
$firstname = $totalResults[$i]['firstname'];
$lastname = $totalResults[$i]['lastname'];
$pcat = $totalResults[$i]['username'];
$outputDisplay .= '<li id='.$contactid.' class="indRes" ';
$outputDisplay .= 'name="'.$contactid.'" >';
$outputDisplay .= '<span style="font-size:10px;cursor:pointer" onclick="getContactsToForm();">';
$outputDisplay .= '<h3>'.$firstname.' ' .$lastname. '</h3>';
$outputDisplay .= '</span>';
$outputDisplay .= '</li>';
}
$outputDisplay .= '</ul>';
$outputDisplay .= "</div>";
return $outputDisplay;
}
function checkOr($searchArray){
if (in_array("OR",$searchArray)){
$orPos = array_search("OR", $searchArray);
if (!empty($orPos)){
$surrVal = "";
$surrVal = --$orPos;
$orValArray = array();
array_push($orValArray,$searchArray[$surrVal]);
$surrVal = $orPos+2;
array_push($orValArray,$searchArray[$surrVal]);
return $orValArray;
}
}
}
?>
//common functinos IUD
<?php
function connectDatabase()
{
$db = mysqli_connect('localhost','root','');
if (!$db)
{
print "<h1>Unable to Connect to mysqli</h1>";
}
$dbname = 'test';
$btest = mysqli_select_db($db, $dbname);
if (!$btest)
{
print "<h1>Unable to Select the Database</h1>";
}
return $db;
}
function selectResults($db, $statement)
{
$output = "";
$outputArray = array();
$db = connectDatabase();
if ($db)
{
$result = mysqli_query($db, $statement);
if (!$result) {
$output .= "ERROR";
$output .= "<br /><font color=red>mysqli No: ".mysqli_errno();
$output .= "<br />mysqli Error: ".mysqli_error();
$output .= "<br />SQL Statement: ".$statement;
$output .= "<br />mysqli Affected Rows: ".mysqli_affected_rows()."</font><br />";
array_push($outputArray, $output);
} else {
$numresults = mysqli_num_rows($result);
$outputArray['resultNum'] = $numresults;
for ($i = 0; $i < $numresults; $i++)
{
$row = mysqli_fetch_array($result);
$outputArray["rowArray"] = $row;
}
}
} else {
array_push($outputArray, 'ERROR-No DB Connection');
}
return $outputArray;
}
function iduResults($db, $statement)
{
$output = "";
$outputArray = array();
$db = connectDatabase();
if ($db)
{
$result = mysqli_query($db, $statement);
if (!$result) {
$output .= "ERROR";
$output .= "<br /><font color=red>mysqli No: ".mysqli_errno();
$output .= "<br />mysqli Error: ".mysqli_error();
$output .= "<br />SQL Statement: ".$statement;
$output .= "<br />mysqli Affected Rows: ".mysqli_affected_rows()."</font><br />";
} else {
$output = mysqli_affected_rows();
}
} else {
$output = 'ERROR-No DB Connection';
}
return $output;
}
?>
My search returns an array that when printed looks like this:
Array(
[0]=>Array
(
[resultNum]=>1
[rowArray]=>Array(
[0]=>1
[userid]=>1
etc
)
)
[1]=>Array
(
[resultNum]=>1
[rowArray]=>Array(
[0]=>2
[userid]=>2
etc
)
)
I want to make the two outer arrays' keys [0],[1] into the search terms that are used in the loop through the getResults($array) function.
Any ideas?
Change
array_push($totalResults, $sqlResults);
to:
$totalResults[$array[$i]] = $sqlResults;
to make it an associative array instead of an indexed array.
P.S. you should learn to use foreach to loop over array elements, and use prepared statements to prevent SQL injection.
Also, selectResults() is only returning the last row of the query. It should be:
} else {
$numresults = mysqli_num_rows($result);
$outputArray['resultNum'] = $numresults;
$outputArray['rowArray'] = array();
for ($i = 0; $i < $numresults; $i++)
{
$row = mysqli_fetch_array($result);
array_push($outputArray["rowArray"], $row);
}
so that it returns all the rows instead of overwriting rowArray each time through the loop.
I have an SQL-database where I read out data that are then shown in a dynamically generated html-table. Here is my code that works fine:
$sql = "SELECT $selection FROM $tabelle WHERE $masterarray";
$result = mysqli_query($db, $sql) or die("Invalid query");
$numrows = mysqli_num_rows($result);
$numcols = mysqli_num_fields($result);
$field = mysqli_fetch_fields($result);
if ($numrows > 0) {
echo "<table>";
echo "<thead>";
echo "<tr>";
echo "<th>" . 'Nr' . "</th>";
for($x=0;$x<$numcols;$x++){
echo "<th>" . $field[$x]->name . "</th>";
}
echo "</tr>";
echo "</thead>";
echo "<tbody>";
echo "<tr>";
$nr = 1;
while ($row = mysqli_fetch_array($result)) {
echo "<td>" . $nr . "</td>";
for ($k=0; $k<$numcols; $k++) {
echo "<td>" . $row[$k] . "</td>"; //Prints the data
}
$nr = $nr + 1;
echo "</tr>";
}
echo "</tbody>";
echo "</table>";
}
}
mysqli_close($db);
Now, I want to remove specific columns (e.g. those, which are empty or those, which are not that interesting for the user, who makes the request).
I tried it with unset($field[$variable]), however, it didn't work. In addition, the values (if there are any), should be removed, too.
can let mysql filter them out for you,
$sql = "SELECT $selection FROM $tabelle WHERE $masterarray AND LENGTH($selection) > 0";
-- http://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_length
Always format the array before you print it. Try to remove the specific columns from the $field array before you echo the HTML and then print the final table. Once the HTML code is echoed in PHP you won't be able to remove it without the use of JavaScript.
You can check against the $field[$x]->name variable and use continue to skip the column.
<?php
// DataBase Config - http://php.net/manual/pt_BR/pdo.construct.php.
$dsn = 'mysql:host=localhost;dbname=test';
$usr = 'root';
$pwd = '';
try { // try to connect in database.
$pdo = new PDO($dsn, $usr, $pwd);
} catch (PDOException $e) { // if there is error in the connection.
die('Connection failed: ' . $e->getMessage());
}
// Prepare Statement and execute - http://php.net/manual/pt_BR/pdo.prepare.php.
$stm = $pdo->prepare('select id, weight, color, name from product');
$stm->execute();
// Get ALL rows - Object.
$rows = $stm->fetchAll(PDO::FETCH_OBJ);
// Print Rows.
//echo '<pre>'.print_r(rows, true).'</pre>';
// Check $row;
if (count($rows)) {
// Order and Display Cols.
$colsDisplay = [
'id' => 'ID Product',
'name' => 'Name',
'weight' => 'Weigth'
];
// Table.
$html = '<table border="1">';
$html .= "\n <thead>";
$html .= "\n <tr>";
$html .= "\n <th bgcolor='#eee'>Row</th>";
$html .= "\n <th>". implode("</th>\n <th>", $colsDisplay) ."</th>";
$html .= "\n </tr>";
$html .= "\n </thead>";
$html .= "\n <tbody>";
// Loop ROWS.
foreach ($rows as $key => $val) {
$html .= "\n <tr>";
$html .= "\n <td bgcolor='#eee'>". $key ."</td>";
// Loop COLS to display.
foreach ($colsDisplay as $thKey => $thVal) {
$html .= "\n <td>". $val->$thKey ."</td>";
}
$html .= "\n </tr>";
}
$html .= "\n".' </tbody>';
$html .= "\n".'</table>';
echo $html;
}
In order to know that a column is empty, you should check the whole column. There are different ways to do it, one of them could be investigating which of them are empty and then only using those that aren't empty. Something like this:
<?php
// ...
$q = "SELECT SUM(LENGTH(my_first_column)) col_0, SUM(LENGTH(my_second_column)) col_1, ..., SUM(LENGTH(my_11th_column)) col_10 FROM $tabelle WHERE $masterarray";
// ... execute query and return results in $nonEmpty
$nonEmpty = array();
foreach($row as $columnIndex) {
if ($row[$columnIndex] > 0) {
$nonEmpty[] = $columnIndex;
}
}
// ... now go through results and print only cols with at least one row with lenght > 0 i.e. non empty
$len = 11;
$rowHTML = "<tr>";
while ($row = mysqli_fetch_array($result)) {
for ($i = 0; $i < $len; ++$i) {
$rowHTML = '';
if (!in_array($i, $nonEmpty)) {
$rowHTML .= '<td>' . $row[$i] . '</td>';
}
$rowHTML .= "</tr>\n";
}
}
// ...
This chunk of code will remove columns with ALL empty values. If you have at least one cell in the column with some value, you'll see the column in your result.
The code isn't optimized - it's just a rough idea. But it's a starting point.
I have been asked to revise an existing site, it's still using PHP5.3 and an old version of PHPmyDirectory, and the code is a little messy.
I'm trying to revise it to just display the list of cities in two columns. I'm trying to do it as a table, as it seemed easiest, but I could also just pull the results into to side by side divs, as there are never more than 26 cities listed (so first half or first 13 in div one, the rest in div two).
Here's the existing original code (I know its not mysqli, but we'll be redoing this site shortly so there's no sense trying to redo a million pages of code right now):
function create_service_area($title) {
global $listing;
$sql = "SELECT state_id, city_id FROM " .T_LISTINGS_CITIES. " WHERE listing_id = {$listing['id']} " ;
$result = query($sql);
if(!$result){
$output = "<p>Call for Service Area!</p>";
}
else {
$output = "<p>";
$result_array = array();
while ($service = fetch_array($result))
{
$sql2 = "SELECT title FROM " .T_LOCATIONS. " WHERE id = {$service['city_id']} " ;
$result2 = query($sql2);
if(!$result2){
break;
} else {
while ($service2 = fetch_array($result2))
{
$output .= "{$service2['title']}";
$title_array = explode(',', $service2['title']);
$result_array[] = $title_array;
}
$output .= "<br/>";
}
}
if($listing['custom_103'] =="Yes") {
$output .= "<b>".$title." will travel for an additional fee!</b></p>";
} else {
$output .="</p>";
}
}
return $output;
}
This is what is looks like currently: Current Site
Here's what I've tried to do:
function create_service_area($title) {
global $listing;
$sql = "SELECT state_id, city_id FROM " .T_LISTINGS_CITIES. " WHERE listing_id = {$listing['id']} " ;
$result = query($sql);
if(!$result){
$output = "<p>Call for Service Area!</p>";
}
else {
$result_array = array();
while ($service = fetch_array($result)) {
$sql2 = "SELECT title FROM " .T_LOCATIONS. " WHERE id = {$service['city_id']} " ;
$result2 = query($sql2);
$i=0;
if(!$result2) {
break;
}
else {
while ($service2 = fetch_array($result2)) {
$output .= "{$service2['title']}";
$title_array = explode(',', $service2['title']);
$result_array[] = $title_array;
$i++;
}
echo "<table>";
for ($j=0; $j<$i; $j=$j+2) {
echo "<tr>";
echo "<td>".$title_array[$j]."</td><td>".$title_array[$j+1]."</td>";
echo "</tr>";
}
echo "</table>";
}
}
if($listing['custom_103'] =="Yes") {
$output .= "<p><b>".$title." will travel for an additional fee!</b></p>";
}
else {
$output .="";
}
}
return $output;
}
And here's what I'm getting: DEV site
I'm very much a PHP newbie, and my understanding is pretty spotty, but I've tried a bunch of different solutions I've found here, and can't get them to work. I'm sure I'm missing something obvious.
Thanks for any pointers!
if I got it correct you should change your
else {
$output = "<p>";
$result_array = array();
while ($service = fetch_array($result))
{
$sql2 = "SELECT title FROM " .T_LOCATIONS. " WHERE id = {$service['city_id']} " ;
$result2 = query($sql2);
if(!$result2){
break;
} else {
while ($service2 = fetch_array($result2))
{
$output .= "{$service2['title']}";
$title_array = explode(',', $service2['title']);
$result_array[] = $title_array;
}
$output .= "<br/>";
}
}
if($listing['custom_103'] =="Yes") {
$output .= "<b>".$title." will travel for an additional fee!</b></p>";
} else {
$output .="</p>";
}
}
with
else {
$output = "<table>";
$result_array = array();
$even_odd=true;
while ($service = fetch_array($result))
{
$sql2 = "SELECT title FROM " .T_LOCATIONS. " WHERE id = {$service['city_id']} " ;
$result2 = query($sql2);
if(!$result2){
break;
} else {
$output .= "";
while ($service2 = fetch_array($result2))
{
if ($even_odd) {
$output .= '<tr><td>'."{$service2['title']}".'</td>';
$even_odd=false;
} else {
$output .= '<td>'."{$service2['title']}".'</td></tr>';
$even_odd=true;
}
$output .= "{$service2['title']}";
$title_array = explode(',', $service2['title']);
$result_array[] = $title_array;
}
}
}
if($listing['custom_103'] =="Yes") {
$output .= "<b>".$title." will travel for an additional fee!</b></p>";
} else {
if (!$even_odd)$output .="<td></td></tr>";
$output .="</table>";
}
}
Try this, I couldn't test it of course, since I've got no access to the data being loaded.
echo "<table>";
$result_array = array();
while ($service = fetch_array($result))
{
//this will loop multiple times. 7 times for Tony S. in the example.
$sql2 = "SELECT title FROM " .T_LOCATIONS. " WHERE id = {$service['city_id']} " ;
$result2 = query($sql2);
$i=0;
if(!$result2)
{
break;
}
else
{
while ($service2 = fetch_array($result2))
{
$title_array = explode(',', $service2['title']);
$result_array[] = $title_array;
$i++;
}
}
}
for ($j=0; $j < count($result_array); $j++)
{
if ($j % 2 == 0)
{
echo "<tr>";
}
echo "<td>".$result_array[$j][0]." (".$result_array[$j][1].")</td>";
if ($j % 2 == 0)
{
echo "</tr>";
}
if ($j % 2 == 1 && $j == count($result_array)-1)
{
echo "<td></td></tr>";
}
}
echo "</table>";
Paste and replace between this lines:
if(!$result){
$output = "<p>Call for Service Area!</p>";
}
else {
.... PASTE IN HERE ....
}
Building on Kim's code, I was able to get it working with some revisions. I also scrapped the table for divs, since it seems less messy to me and it seemed like the table styling was interfering somehow.
function create_service_area($title) {
global $listing;
$sql = "SELECT state_id, city_id FROM " .T_LISTINGS_CITIES. " WHERE listing_id = {$listing['id']} " ;
$result = query($sql);
if(!$result){
$output = "<p>Call for Service Area!</p>";
} else {
$output = "<div>";
//$result_array = array();
$even_odd=true;
while ($service = fetch_array($result))
{
$sql2 = "SELECT title FROM " .T_LOCATIONS. " WHERE id = {$service['city_id']} " ;
$result2 = query($sql2);
if(!$result2){
break;
} else {
$output .= "{$service2['title']}";
$title_array = explode(',', $service2['title']);
$result_array[] = $title_array;
while ($service2 = fetch_array($result2))
{
if ($even_odd) {
$output .= '<div style="float:left;width:50%;">'."{$service2['title']}".'</div>';
$even_odd=false;
} else {
$output .= '<div style="float:right;width:50%;">'."{$service2['title']}".'</div>';
$even_odd=true;
}
}
}
}
if($listing['custom_103'] =="Yes") {
$output .= "<div style='clear:both;width:90%;float:none;'><p><b>".$title." will travel for an additional fee!</b></p></div>";
} else {
}
}
return $output;
}
Thanks so much Kim and Mouser!
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>";
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>";