Author Topic: MySQL data in a table using MySQLi, TMPL_LOOP and ARRAY_PUSH  (Read 2081 times)

0 Members and 1 Guest are viewing this topic.

Offline ClausVB

  • Administrator
  • Hero Member
  • *****
  • Posts: 566
    • Homepage: clausvb.de
MySQL data in a table using MySQLi, TMPL_LOOP and ARRAY_PUSH
on: Thu, 10. December 2009 - 09:51:48
Sometimes you want to manipulate database rows before they are displayed. Here is an example using MySQLi, TMPL_LOOP and ARRAY_PUSH.


PHP:

Code: [Select]
<?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(HOSTUSERPASSWORDDATABASE);
  
$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:

Code: [Select]
<!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