Create a table X columns wide

Updated pritaeas 3 Tallied Votes 528 Views Share

The following snippet will show, how you can pass a data array to a function, and generate a table with N columns. $data contains some dummy data, which can come from any data source. Then you call createHtmlTable passing the data, the number of columns you want, and a function, which will be called for each row, where you can specify the exact layout of each cell. I hope the comments speak for themselves. If not, please reply and let me know.

<?php
    function createHtmltable($data, $cols, $callback) {
        $result = '<table border="1">';
        $i = 0;
        foreach ($data as $row) {
        
            // starts a new row
            if ($i % $cols == 0)
              $result .= '<tr>';
            
            // outputs a cell
            $result .= '<td>';
            if (is_callable($callback)) {
                // calls the callback function with the current row
                $result .= call_user_func($callback, $row);
            }
            else {
                // if the function cannot be called, add an empty cell
                $result .= '&nbsp;';
            }
            $result .= '</td>';
            
            $i++;
            
            // ends a row
            if ($i % $cols == 0)
              $result .= '</tr>';
        }
        
        // add missing cells if necessary
        if ($i % $cols != 0) {
            while ($i % $cols != 0) {
              $result .= '<td>&nbsp;</td>';
              $i++;
            }
            $result .= '</tr>';
        }
        $result .= '</table>';
        return $result;
    }

    // this function will layout the data for a single cell
    // the $data parameter will contain a single entity
    function createCellContent($data) {
        return "<b>{$data['name']}</b><br/>{$data['title']}</b>";
    }
    
    // data array, taken from some data source
    $data = array (
      0 => array ('name' => 'John', 'title' => 'CEO'),
      1 => array ('name' => 'Peter', 'title' => 'COO'),
      2 => array ('name' => 'Jack', 'title' => 'CIO'),
      3 => array ('name' => 'Marc', 'title' => 'CFO'),
      4 => array ('name' => 'Hans', 'title' => 'Codemonkey')
    );

    // create a table from this data, use two columns
    // and call createCellContent for each cell
    echo createHtmlTable($data, 2, 'createCellContent');
?>
cdoggg94 0 Newbie Poster

Thank you

Someone has sent me this:

<table cellspacing="3" cellpadding="3">
<?php
$query = "SELECT product FROM selling_items ORDER BY prod_id";
$result = mysql_query($query) or die("There was a problem with the SQL query: " . mysql_error()); 
if($result && mysql_num_rows($result) > 0)
{
        $i = 0;
        $max_columns = 3;
        while($row = mysql_fetch_array($result))                
   {
           // make the variables easy to deal with
           extract($row);

           // open row if counter is zero
           if($i == 0)
                  echo "<tr>";

           // make sure we have a valid product
           if($product != "" && $product != null)
                  echo "<td>$product</td>";

           // increment counter - if counter = max columns, reset counter and close row
           if(++$i == $max_columns) 
           {
                   echo "</tr>";
                   $i=0;
           }  // end if 
   } // end while
} // end if results

// clean up table - makes your code valid!
if($i < $max_columns)
{
        for($j=$i; $j<$max_columns;$j++)
                echo "<td>&nbsp;</td>";
}
 ?>
</tr>
</table>

And I am going to try it. If I cant make it work the way I want then I will be sure to give what you sent a try.

Thanks again

pritaeas 2,194 ¯\_(ツ)_/¯ Moderator Featured Poster

That works too. The one I posted is just a little more generic.

cdoggg94 0 Newbie Poster

i appreciate the help

Thanks again

cdoggg94 0 Newbie Poster

I just have a question, where does $product get it value ?

the code asks if its empty or blank, but i dont get where its getting its value, which I think should be the content i want to display..

GliderPilot 33 Posting Whiz

From here:

extract($row);

That's taking the DB Row and turning the assoiative array and turning it into variables named by their array key. in this case the only thing we get is product from the DB so rather than having to type $row['product'] every time the above line lets you just use $product

naphets 0 Junior Poster in Training

what i need is very close to this, maybe this. The thing i am not sure about, is that i am using tables to place ad space on website. so it varies.
So, some ads use 1 row and 1 cloumn, while others use up to 6 rows and several columns. max is 8 columns. there could also be a combination of multiple sizes in a single query result. So it needs to draw the tables on the fly.
Currently i just have multiple tables hand placed, one after the other. I have created a button to click, that succesfully accesses the database & displays the results of query in a dropdown menu. I made this in PHP & embedded it into the html footer (which is where my ads currently) & it displays the resulting ads.
The end result i am looking for, is to only enter the info about each advertisement (javascript), into a database, and it magically changes the table and displays the ads properly.
So,... I would enter an entry indatabase of the javascript link. Also the properties like height & width. also what category it belongs to. I think thats all i need?

Member Avatar for LastMitch
LastMitch

I have created a button to click, that succesfully accesses the database & displays the results of query in a dropdown menu. I made this in PHP & embedded it into the html footer (which is where my ads currently) & it displays the resulting ads. The end result i am looking for, is to only enter the info about each advertisement (javascript), into a database, and it magically changes the table and displays the ads properly.So,... I would enter an entry indatabase of the javascript link. Also the properties like height & width. also what category it belongs to. I think thats all i need?

pritaeas's code snippet doesnt a database. It's just fetching data from the array.

You're asking about inserting data and fetching data.

I think talking about cdoggg94 code not pritaeas's code snippet.

I think it's best to create a new thread about the issue you are having.

So you can explain more about the issue you are having.

The purpose of pritaeas's code snippet is to learn and understand how it works.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.