Dynamic table

  • KanJay
  • Born
  • Born
  • KanJay
  • Posts: 4

Post 3+ Months Ago

I’m trying to create dynamic table in PHP with 3 columns in a singe row where the content will be taken from a database. The no of rows are unlimited. Can somebody send me a sample script?
  • Anonymous
  • Bot
  • No Avatar
  • Posts: ?
  • Loc: Ozzuland
  • Status: Online

Post 3+ Months Ago

  • gisele
  • Expert
  • Expert
  • User avatar
  • Posts: 585
  • Loc: Nimes (France)

Post 3+ Months Ago

PHP Code: [ Select ]
$results = mysql_query($query)or die (mysql_error()."<br />".$query);
//just initialize like that :
$my_array = array();
//and then in the loop that browse the records set :
$i = 0;
while($data = mysql_fetch_assoc($results))
{
   $my_array[$i][0] = $data["field1"];
   $my_array[$i][1] = $data["field2"];
   $my_array[$i][2] = $data["field3"];
   $i++;
}
//print_r($my_array);//you can check howdoes look the table with print_r()
 
  1. $results = mysql_query($query)or die (mysql_error()."<br />".$query);
  2. //just initialize like that :
  3. $my_array = array();
  4. //and then in the loop that browse the records set :
  5. $i = 0;
  6. while($data = mysql_fetch_assoc($results))
  7. {
  8.    $my_array[$i][0] = $data["field1"];
  9.    $my_array[$i][1] = $data["field2"];
  10.    $my_array[$i][2] = $data["field3"];
  11.    $i++;
  12. }
  13. //print_r($my_array);//you can check howdoes look the table with print_r()
  14.  


you could also use arry_push() but I'm not sure it'll optimize the performance.
  • Tannu4u
  • Proficient
  • Proficient
  • User avatar
  • Posts: 480
  • Loc: India

Post 3+ Months Ago

PHP Code: [ Select ]
//CREATE CONNECTION TO THE DATABASE
$link = mysql_connect("localhost", "tannu", "tannu");
 
if($link)
{
 mysql_select_db("testDB", $link);
}
//CREATE TABLE QUERY
$strQuery = "Create table dynamic{col1 var 256, col2 var 256, col3 var 256}";
 
mysql_query($strQuery);
  1. //CREATE CONNECTION TO THE DATABASE
  2. $link = mysql_connect("localhost", "tannu", "tannu");
  3.  
  4. if($link)
  5. {
  6.  mysql_select_db("testDB", $link);
  7. }
  8. //CREATE TABLE QUERY
  9. $strQuery = "Create table dynamic{col1 var 256, col2 var 256, col3 var 256}";
  10.  
  11. mysql_query($strQuery);
  • gisele
  • Expert
  • Expert
  • User avatar
  • Posts: 585
  • Loc: Nimes (France)

Post 3+ Months Ago

HI, okay,maybe I hadn't got the question :-)
  • joebert
  • Fart Bubbles
  • Genius
  • User avatar
  • Posts: 13502
  • Loc: Florida

Post 3+ Months Ago

This works ok for simple situations & mysql.
Give it some details at the top & it should take care of the rest

PHP Code: [ Select ]
<html>
<head>
<title>Table</title>
<style type="text/css">
th, td{
   font: 11px Verdana;
}
.r0{
   background-color: #eee;
}
.r1{
   background-color: #ccc;
}
th{
   background-color: #555;
   color: #fff;
}
</style>
</head>
<body>
<?php
   // Details, details, details
   $server = 'localhost';
   $username = 'root';
   $pass = 'pass';
   $database = 'phpbb2';
   $table_name = 'phpbb_users';
 
   // No mans land
   
   // Connect, select DB
   $db = mysql_connect($server, $username, $pass); mysql_query("use $database");
   
   // Template
   $table = "<table><thead>%s</thead><tbody>%s</tbody></table>";
   $tbody = '';
   $thead = '<tr>';
   
   // Fetch a list of fields from the table
   $resource = mysql_query("SHOW COLUMNS FROM `$table_name`");
   
   // Create a CONCAT_WS query from the list of fields
   // CONCAT_WS works like implode in a way, the first argument is the glue that holds the rest of the arguments together.
   $concat = 'CONCAT_WS("</td><td>"';
   while($details = mysql_fetch_assoc($resource))
   {
      $thead .= '<th>' . $details['Field'] . '</th>'; // Build the table header while we're here
      $concat .= ',' . $details['Field']; // Add an argument to CONCAT_WS
   }
   $thead .= '</tr>'; // Close the table header
   $concat .= ')'; // Close the CONCAT_WS query
   
   // Get the results of the CONCAT_WS query
   $sql = "SELECT $concat FROM `$table_name`";
   $resource = mysql_query($sql);
   if(! $resource){
      die(mysql_error());
   }
   
   // Now it's a matter of appending the pre-formatted rows returned from the query to a string &
   // then using sprintf to put that all together.
   $i = 0;
   while($row = mysql_fetch_row($resource))
   {
      $tbody .= '<tr class="r' . ($i%2) . '"><td>' . implode('', $row) . '</td></tr>';
      $i++;
   }
   echo sprintf($table, $thead, $tbody);
   // Now, if we could only get people to arrange their database columns in certain ways...
?>
</body>
</html>
  1. <html>
  2. <head>
  3. <title>Table</title>
  4. <style type="text/css">
  5. th, td{
  6.    font: 11px Verdana;
  7. }
  8. .r0{
  9.    background-color: #eee;
  10. }
  11. .r1{
  12.    background-color: #ccc;
  13. }
  14. th{
  15.    background-color: #555;
  16.    color: #fff;
  17. }
  18. </style>
  19. </head>
  20. <body>
  21. <?php
  22.    // Details, details, details
  23.    $server = 'localhost';
  24.    $username = 'root';
  25.    $pass = 'pass';
  26.    $database = 'phpbb2';
  27.    $table_name = 'phpbb_users';
  28.  
  29.    // No mans land
  30.    
  31.    // Connect, select DB
  32.    $db = mysql_connect($server, $username, $pass); mysql_query("use $database");
  33.    
  34.    // Template
  35.    $table = "<table><thead>%s</thead><tbody>%s</tbody></table>";
  36.    $tbody = '';
  37.    $thead = '<tr>';
  38.    
  39.    // Fetch a list of fields from the table
  40.    $resource = mysql_query("SHOW COLUMNS FROM `$table_name`");
  41.    
  42.    // Create a CONCAT_WS query from the list of fields
  43.    // CONCAT_WS works like implode in a way, the first argument is the glue that holds the rest of the arguments together.
  44.    $concat = 'CONCAT_WS("</td><td>"';
  45.    while($details = mysql_fetch_assoc($resource))
  46.    {
  47.       $thead .= '<th>' . $details['Field'] . '</th>'; // Build the table header while we're here
  48.       $concat .= ',' . $details['Field']; // Add an argument to CONCAT_WS
  49.    }
  50.    $thead .= '</tr>'; // Close the table header
  51.    $concat .= ')'; // Close the CONCAT_WS query
  52.    
  53.    // Get the results of the CONCAT_WS query
  54.    $sql = "SELECT $concat FROM `$table_name`";
  55.    $resource = mysql_query($sql);
  56.    if(! $resource){
  57.       die(mysql_error());
  58.    }
  59.    
  60.    // Now it's a matter of appending the pre-formatted rows returned from the query to a string &
  61.    // then using sprintf to put that all together.
  62.    $i = 0;
  63.    while($row = mysql_fetch_row($resource))
  64.    {
  65.       $tbody .= '<tr class="r' . ($i%2) . '"><td>' . implode('', $row) . '</td></tr>';
  66.       $i++;
  67.    }
  68.    echo sprintf($table, $thead, $tbody);
  69.    // Now, if we could only get people to arrange their database columns in certain ways...
  70. ?>
  71. </body>
  72. </html>
  • Tannu4u
  • Proficient
  • Proficient
  • User avatar
  • Posts: 480
  • Loc: India

Post 3+ Months Ago

I think that he wants to create a database table dynamically. Please correct me if i am wrong. :)
  • Rabid Dog
  • Web Master
  • Web Master
  • User avatar
  • Posts: 3245
  • Loc: South Africa

Post 3+ Months Ago

it sounds like he is trying to create something similiar to an ADO dataset.
  • joebert
  • Fart Bubbles
  • Genius
  • User avatar
  • Posts: 13502
  • Loc: Florida

Post 3+ Months Ago

Quote:
where the content will be taken from a database


That suggests to me that this is somthing outside the scope of the database.
  • Rabid Dog
  • Web Master
  • Web Master
  • User avatar
  • Posts: 3245
  • Loc: South Africa

Post 3+ Months Ago

okay so if I understand correctly.

You have a db
You have a table with three columns
Unlimited rows (which is pretty normal)
And you want to create a table in PHP.

Looking at Joebert's response I am willing to bet that is what you are looking for.

So effectively the question would be to create and HaTeML table dynamically using php.

I think everyone assumed the table was a db table. The reason I suggested something like an ADO Dataset is because the dataset can act as a store for information without having to use a db. I did this once for sorting files in directory and executing an SQL type query against the dataset to order them by date.
  • UberGeek
  • Born
  • Born
  • User avatar
  • Posts: 4

Post 3+ Months Ago

Wow that seems very complex, and I tend to be very simple.

I do this on a very regular basis

I use this function to connect to a database
Code: [ Select ]
function DatabaseQuery($SelectedDataBase="",$Query){
 $Server = 'localhost';
 $User = 'User';
 $Pass='Pass';    
 $dbc = mysql_connect ($Server,$User,$Pass) or die('Could Not connect - '. mysql_error() . mysql_errno());
 mysql_select_db ($SelectedDataBase) or die('Could not  use '.$SelectedDataBase);
 $result=mysql_query($Query);
 mysql_close();
 return $result;
}
  1. function DatabaseQuery($SelectedDataBase="",$Query){
  2.  $Server = 'localhost';
  3.  $User = 'User';
  4.  $Pass='Pass';    
  5.  $dbc = mysql_connect ($Server,$User,$Pass) or die('Could Not connect - '. mysql_error() . mysql_errno());
  6.  mysql_select_db ($SelectedDataBase) or die('Could not  use '.$SelectedDataBase);
  7.  $result=mysql_query($Query);
  8.  mysql_close();
  9.  return $result;
  10. }


This makes the connection and query on the same line of code through the rest of your program.

Then I generate the table

Code: [ Select ]
$Table = '<table><tr><th>1st</th><th>2nd</th><th>3rd</th></table>';
$Query= "Select First,Second,Third from Table";
$Database='test';
$result=DatabaseQuery($Database,$Query);
while ($TableRow=mysql_fetch_assoc($result)){
 $Table .= '<tr><td>'.$TableRow['First'].'</td><td>'.$TableRow['Second'].'</td><td>'.$TableRow['Third'].'</td><tr>';
}
$Table .= '</table>';
echo $Table;
  1. $Table = '<table><tr><th>1st</th><th>2nd</th><th>3rd</th></table>';
  2. $Query= "Select First,Second,Third from Table";
  3. $Database='test';
  4. $result=DatabaseQuery($Database,$Query);
  5. while ($TableRow=mysql_fetch_assoc($result)){
  6.  $Table .= '<tr><td>'.$TableRow['First'].'</td><td>'.$TableRow['Second'].'</td><td>'.$TableRow['Third'].'</td><tr>';
  7. }
  8. $Table .= '</table>';
  9. echo $Table;


I like the reusablility the function offers and the simplicity to remember that the mysql_fetch_assoc gives.
  • Rabid Dog
  • Web Master
  • Web Master
  • User avatar
  • Posts: 3245
  • Loc: South Africa

Post 3+ Months Ago

Joes code allows for a change in table structure, yours only allows for three columns. So now if you encapsulate you code you would have to have variations for the number of columns.

Joes code already provides for it.
  • Nosf
  • Born
  • Born
  • Nosf
  • Posts: 1

Post 3+ Months Ago

Quote:
<?php
include 'config.php'; //you can define config.php or you can just connect from this file...

// how many rows to show per page
$rowsPerPage = 20; // this is where you can define how many rows would you like to display

// by default we show first page
$pageNum = 1;
$tablica = "something"; //you can define table here

if $_GET['page'] // defined, use it as page number
if(isset($_GET['page']))
{
$pageNum = $_GET['page'];
}

// counting the offset
$offset = ($pageNum - 1) * $rowsPerPage;

$query = "SELECT id, proizvod, cijena, tekst, slika
FROM $tablica "; //my teorethical db fields

$pagingQuery = "LIMIT $offset, $rowsPerPage";
$result = mysql_query($query . $pagingQuery) or die('Error, query failed');

// ispis
echo '<br><br><br><br><br><table align="center" border="5"><tr>';
$i = 1;
while(list($id, $proizvod, $cijena, $tekst, $slika) = mysql_fetch_array($result))
{

echo "<td align='center' height='120' width='160'>$slika<br>$proizvod<br>$cijena</b></td>
<p>$tekst</p>";

// here where i did some check cause I needed table 4x5 in dimensions.
if ($i==4) {echo "</tr><tr>";}
if ($i==8) {echo "</tr><tr>";}
if ($i==12) {echo "</tr><tr>";}
if ($i==16) {echo "</tr><tr>";}
if ($i==20) {echo "</tr><tr>";}


$i++;
}

echo '</tr></table>';
echo '<br>';

// how many rows we have in database
$result = mysql_query($query) or die('Error, query failed');
$numrows = mysql_num_rows($result);

// how many pages we have when using paging?
$maxPage = ceil($numrows/$rowsPerPage);

$self = $_SERVER['PHP_SELF'];

// creating 'previous' and 'next' link
// plus 'first page' and 'last page' link

// print 'previous' link only if we're not
// on page one
if ($pageNum > 1)
{
$page = $pageNum - 1;
$prev = " <a href=\"$self?page=$page\">prev</a> ";

$first = " <a href=\"$self?page=1\">first</a> ";
}
else
{
$prev = '..prev..'; // we're on page one, don't enable 'previous' link
$first = '..first..'; // nor 'first page' link
}

// print 'next' link only if we're not
// on the last page
if ($pageNum < $maxPage)
{
$page = $pageNum + 1;
$next = " <a href=\"$self?page=$page\">next</a> ";

$last = " <a href=\"$self?page=$maxPage\">last</a> ";
}
else
{
$next = '..next..'; // we're on the last page, don't enable 'next' link
$last = '..last..'; // nor 'last page' link
}

// print the page navigation link
echo "<div align='center'>";
echo $first . $prev . " Showing page <strong>$pageNum</strong> out of <strong>$maxPage</strong>" . $next . $last;
echo "</div>";



Ok, for a similar problem I am using this code.
Sorry for bad english.

Maybe I didn't understood the question, but i guess this script could help.
  • Muscles
  • Born
  • Born
  • Muscles
  • Posts: 1

Post 3+ Months Ago

Hi, thanks for the code Joe. However, I've got a slight request here, where is it possible to change the font for the tables, and is there any possible way i could write some prefix html code for some of my data so that I can make it a link.. ie <a href='$link'>$link</a> or something like that? If not its fine, but I really need to know how to change the font/use my css command of
Code: [ Select ]
<p class="style1"> ...</p>


Where would I put that, each time I try to put it somewhere i get an error, so where exactly does it go?

Here's the page I wanted to do it on http://sumitkhan.com/lfc/links.php

Any help would be appreciated!

Cheers

Post Information

  • Total Posts in this topic: 13 posts
  • Users browsing this forum: No registered users and 125 guests
  • You cannot post new topics in this forum
  • You cannot reply to topics in this forum
  • You cannot edit your posts in this forum
  • You cannot delete your posts in this forum
  • You cannot post attachments in this forum
 
 

© 1998-2014. Ozzu® is a registered trademark of Unmelted, LLC.