Sometimes you want to manipulate database rows before they are displayed. Here is an example using MySQLi, TMPL_LOOP and ARRAY_PUSH.
PHP:<?php
if (php == $_GET[showsource])
{
show_source($_SERVER[SCRIPT_FILENAME]);
exit;
}
elseif (html == $_GET[showsource])
{
show_source(dirname(__FILE__) . /tmpl/db.htm);
exit;
}
require_once vlib/vlibTemplate.php;
require_once vlib/vlibDate.php;
require_once db_config.php;
// Creating objects
$db = new mysqli(HOST, USER, PASSWORD, DATABASE);
$tmpl = new vlibTemplate(tmpl/db.htm);
$date = new vlibDate(de); // you may set this to en (english)
// database query
$select = SELECT name, birthday, city FROM . TABLE;
$result = $db->query($select)
or die(Error on SELECT:<br /> . $db->error . <pre> . $select . </pre>);
// creating LOOP-Array and parse template
$table_data = array();
while ($row = $result->fetch_assoc())
{
array_push(
$table_data,
array(
name => $row[name],
birthday => $date->formatDate($row[birthday], %A, %d. %B %Y),
city => $row[city]
)
);
}
$tmpl->setloop(table_data, $table_data);
$tmpl->pparse();
// Call destruct
$db->close();
unset($db);
unset($tmpl);
?>
Template:<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
<title>MySQL data in a table using MySQLi, TMPL_LOOP and ARRAY_PUSH</title>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
</head>
<body>
<table border="1" width="70%" summary="MySQL data in a table using MySQLi, TMPL_LOOP and ARRAY_PUSH">
<caption>MySQL data in a table using MySQLi, TMPL_LOOP and ARRAY_PUSH</caption>
<thead>
<tr>
<th align="left">name</th>
<th align="left">birthday</th>
<th align="left">city</th>
</tr>
</thead>
<tbody>
<tmpl_loop name=table_data>
<tr>
<td valign="top">{tmpl_var name=name}</td>
<td valign="top">{tmpl_var name=birthday}</td>
<td valign="top">{tmpl_var name=city}</td>
</tr>
</tmpl_loop>
</tbody>
</table>
<p><a href="db.php?showsource=php">show PHP code</a> |
<a href="db.php?showsource=html">show template (HTML code)</a></p>
</body>
</html>
MySQL data in a table using MySQLi, TMPL_LOOP and ARRAY_PUSH