PbClasses - PbTpl-Tutorial

Example 5 - Showing data from database table

In this example we will display a whole table from the database using the class SqlPdo from PbClasses.

Example table from database

id first_name last_name address city state zip
1 John Doe 123 Maple St Springfield IL 62704
2 Jane Smith 456 Oak Ave Madison WI 53703
3 Emily Johnson 789 Pine Rd Austin TX 73301
4 Michael Brown 321 Birch Blvd Denver CO 80202
5 Sarah Davis 654 Cedar Dr Portland OR 97201
6 David Miller 987 Spruce Ln Seattle WA 98101
7 Laura Wilson 111 Elm St Boston MA 02108
8 Daniel Taylor 222 Ash Ct Chicago IL 60601
9 Sophia Anderson 333 Fir Way San Diego CA 92101
10 James Thomas 444 Willow Pkwy Phoenix AZ 85001
PHP-Code
<?php
use PbClasses\PbTpl;
use 
MyProject\DbConnection;
use 
PbClasses\Util\Filter;

try {
    
$db DbConnection::get();
    
$table 'customer';
    
$rowsArr $db->selectAssoc($table); //We want all.   
} catch (\Exception $exc) {
    echo 
$exc->getMessage(); 
    exit;
}

try {
    
$c = new PbTpl('./templates/content_05.tpl');
    
$seRe = [
        
//building the headline from the keys of the first row.
        
'head_row' => getHeadRow($carray_keys($rowsArr[0])), 

        
'body_rows' => getBodyRows($c$rowsArr)
    ];
    return 
$c->fillTpl('content'$seRe);
    
} catch (
\Exception $exc) {
    echo 
$exc->getMessage();
    exit;
}

function 
getHeadRow($c$keyArr) {
    return 
$c->fillRowTpl('th''entry'$keyArr);
}

function 
getBodyRows($c$rowsArr) {
    
$rowBuffer '';
    
    foreach(
$rowsArr as $row) {
        
//The values from the table should be masked with htmlentities.
        //We use the filter class that was introduced in the previous eyample.
        
$tdRow $c->fillRowTpl('td''entry'Filter::numericArr(array_values($row)));
        
$rowBuffer .= $c->fillTpl('body_row''td_row'$tdRow);
    }
    return 
$rowBuffer;
    
}

Template-Code

[content]

<h3>Example table from database</h3>
<table>
    <tr>{HEAD_ROW}</tr>
    {BODY_ROWS}
</table>

###################
[th]
<th>{ENTRY} </th>

[body_row]
<tr>{TD_ROW}</tr>

[td]
<td>{ENTRY}</td>