I am relatively new to php and have a feeling that I am going the long way round when displaying data from mysql.
I have a table a I want to show a few fields from my database.
How would I achieve this without having to echo every bit of the table???
Here is the code:
<?php
$query1 = mysql_send("SELECT firstname, lastname, email, user, country FROM customers WHERE id='".$_COOKIE['custid']."'");
while ($row = mysql_fetch_array($query1))
{
echo ' <table id="account_table" style="width:550px; border:none; ">
<tr>
<td width="155">Contact Name</td>';
echo '<td width="335">';
echo $row['firstname'] ;
echo ' ';
echo $row['lastname'];
echo '</td>
</tr>
<tr>
<td>Email Address</td>
<td>';
echo $row['email'];
echo ' </td>
</tr>
<tr>
<td>Username</td>
<td>' ;
echo $row['user'];
echo '</td>
</tr>
<tr>
<td>Country</td>
<td>';
echo $row['country'];
echo '</td>
</tr>
<tr>
<td>Time Zone</td>
<td>GMT+1</td>
</tr>
<tr>
<td>Activated</td>
<td>16 Dec 2009</td>
</tr>
</table>';
}
?>
You can fetch all data into an array first and then iterate over that array. There is no need to echo all that HTML with PHP.
At the top of your file, you should do all the processing (i.e. getting, validating data) and in the remainder you just write plain HTML, only printing the values with PHP.
This already gives you a certain degree of separation. Others mention template engines (Smarty, etc.). I don't think that you really need that, because PHP itself is a template engine.
Just don't get tempted to do sophisticated stuff in your presentation ;)
Also the alternative syntax for control structures is very useful for using in combination with the presentation as it is imho much more readable.
I changed the table structure a bit, because you were not generation valid HTML (you create a lot tables with the same ID in your original code).
This just generates one table, with a row for each customer.
<?php
$customers = array();
$query1 = mysql_send("SELECT firstname, lastname, email, user, country FROM customers WHERE id='".$_COOKIE['custid']."'");
while ($row = mysql_fetch_array($query1)) {
$cusomters[] = $row;
}
?>
<table id="account_table" style="width:550px; border:none;">
<tr>
<th width="155">Contact Name</th>
<th>Email Address</th>
<th>Username</th>
<th>Country</th>
<th>Time Zone</th>
<th>Activated</th>
</tr>
<?php foreach($customers as $customer): ?>
<tr>
<td width="335">
<?php echo $row['firstname'] ?>
<?php echo $row['lastname'] ?>
</td>
<td><?php echo $row['email'] ?> </td>
<td><?php echo $row['user'] ?></td>
<td><?php echo $row['country'] ?></td>
<td>GMT+1</td>
<td>16 Dec 2009</td>
</tr>
<?php endforeach; ?>
</table>