Logically, the simplest way is to run two processes:
1) Generate data values to be displayed (arrays, numbers, usernames, whatever....)
2) include() a .php file which makes use of those values
Imagine displaying a list of users:
Generate data
Code: Select all
$userList = array(); //For the template
$sql = 'SELECT userid, username FROM users';
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result))
{
$userList[$row['userid']] = $row['username'];
}
include('some-template.php');
Code: Select all
<table>
<thead>
<tr>
<th>ID</th>
<th>Username</th>
</tr>
</thead>
<tbody>
<?php foreach ($userList as $userid => $username): ?>
<tr>
<td><?php echo $userid; ?></td>
<td><?php echo $username; ?></td>
</tr>
<?php endforeach; ?>
</table>
This is the *very* basic logic involved. To take it a step further and clean things up a bit you'd encapsulate those two concerns (generating model data, and displaying a template) into two different components.
At a really basic level that could just be two functions:
Code: Select all
function get_users()
{
$userList = array(); //For the template
$sql = 'SELECT userid, username FROM users';
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result))
{
$userList[$row['userid']] = $row['username'];
}
//Return data for the template
return array('userList' => $userList);
}
function include_template($path, $_data = array())
{
foreach ($_data as $_k => $_v)
{
$$_k = $_v; //Create variable-variables (see php.net)
}
include($path);
}
Now you can have one place where you pull those two together.
Code: Select all
$modelData = get_users();
include_template('some-template.php', $modelData);
Taking it a step further you'd move away from using those functions and start creating classes... and so on...