that is still a mixture of PHP and HTML, consider this example
PHP Code:
interface ResultReplace
{
public function replace($template);
}
class Base implements ResultReplace
{
protected
$u_username,
$u_firstName,
$u_lastName
;
public function replace($template)
{
$str = $template;
$str = str_replace("_%USER%_", $this->u_username, $str);
$str = str_replace("_%FIRST%_", $this->u_firstName, $str);
$str = str_replace("_%LAST%_", $this->u_lastName, $str);
return $str;
}
}
class User extends Base
{
protected $html = '';
public function __construct($tpl)
{
$this->html = $tpl;
}
public function __toString()
{
return $this->replace($this->html);
}
}
try
{
// set your database credentials here
$pdo = new PDO($dsn, $user, $pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$html = file_get_contents(TEMPLATE_DIR . "user.inc")
if (false === $html)
{
throw new Exception("Failed to load template 'user.inc'.");
}
/* user.inc:
<div class="user">
<strong>_%USER%_</strong>
<em>_%FIRST%_ _%LAST%_</em>
</div>
*/
$ps = $pdo->query("SELECT `u_username`, `u_firstName`, `u_lastName` FROM `userTable`");
$ps->setFetchMode(PDO::FETCH_CLASS, "User", array($html));
foreach($ps as $user)
{
echo $user;
}
}
catch (Exception $e)
{
echo "We’re sorry, there seems to be a problem.";
error_log($e->getMessage());
}
if you add autoloading, the real fun starts.