Sunday, April 19, 2009

a simple content management system: part three

Now for the PHP coding part. Firstly, I needed to build a web page called index.php that displayed the records from my data source. The code below demonstrates connecting to the database and querying my contacts table for this data:

<?php
// Connect database.
$host=""; // Host name.
$db_user=""; // MySQL username.
$db_password=""; // MySQL password.
$database=""; // Database name.
mysql_connect($host,$db_user,$db_password);
mysql_select_db($database);
// Select all data records in table "name_list" and put them into $result.
$sql = "select * from contacts order by last_name asc";
$qContacts = mysql_query($sql);
?>

Then, within the <body> tags of the HTML, I added the following form, which was written in HTML, but includes PHP in order to bind the data from my database table to the web page display:
<form name="contacts_form">
<table border="1" cellpadding="3" cellspacing="0">
<tr>
<th> </th>
<th>Last Name</th>
<th>First Name</th>
<th>Phone</th>
<th>E-mail</th>
<th>Edit</th>
<th>Delete</th>
</tr>
<?php
// Create a variable to display row numbers
$row_counter = 1;
// Get all the records returned from the $qContacts database query.
// Loop over each record returned and put all the data into a variable called $row.
while($row=mysql_fetch_array($qContacts)){
?>
<tr>
<td><?php echo $row_counter; ?></td>
<td><?php echo $row['last_name']; ?></td>
<td><?php echo $row['first_name']; ?></td>
<td><?php echo $row['phone']; ?></td>
<td><?php echo $row['email']; ?></td>
<td><a href="update.php?action=edit&id=<?php echo $row['contact_id']; ?>">Edit</a></td>
<td><a href="update.php?action=del&id=<?php echo $row['contact_id']; ?>">Delete</a></td>
</tr>
<?php
// Increment the current value of $row_counter by 1.
$row_counter++;
} // End loop.
?>
</table>
</form>

0 comments:

  © 2009. Template by Ourblogtemplates.com.