Exercise 8

PHP and MySQL access

1. Start with a simple table in the database:

mysql > SELECT * FROM employees

In the following exercises I used a MySQL tool called HeidiSql

Here are some screen shots of the exercise:

table

table_prop

select

2. Create a web page with the following PHP:

<?php
$db = mysql_connect("farrer.csu.edu.au", "keustace", "password");
$result = mysql_query("SELECT * FROM employees", $db);
echo "First Name: ", mysql_result($result, 0, "first"), "<BR>";
echo "Last Name: ", mysql_result($result, 0, "first"), "<BR>";
echo "Address: ", mysql_result($result, 0, "first"), "<BR>";
echo "Position: ", mysql_result($result, 0, "first"), "<BR>";
?>

Here is a screenshot of the code and the rendered pages:

8_2_code

8_2_result

3. This is how we can add a record and is part of a file to create called add_record.html:

<HTML>
<BODY>
<FORM METHOD="POST" ACTION="add_record.php">

First Name: <INPUT TYPE="Text" NAME="first">
Last Name: <INPUT TYPE="Text" NAME="last">
Address: <INPUT TYPE="Text" NAME="address">
Position: <INPUT TYPE="Text" NAME="position">
<INPUT TYPE="Submit" NAME="submit" VALUE="Enter information">

</FORM>
</BODY>
</HTML>

My HTML page:

8_3_code
And rendered:

8_3_result

4. The corresponding PHP file is add_record.php used with the POST method:

<?php
$db = mysql_connect("farrer.csu.edu.au", "keustace", "password");
mysql_select_db("mydatabase", $db);
$result = mysql_query("INSERT INTO employees (first, last, address, position) VALUES ('$first', '$last', '$address', '$position')");
if ($result == 1) {echo "Thank you!" Your information has been entered.";
}else{
echo "Sorry, there's a problem";
}
?>

My PHP page:

8_4_code
Enter some data:

8_4_result1
Display a diagnostic message after processing:

8_4_result2
Check that the data has been added to the database:

8_4_result3

5. The last code example shows how to get multiple records:

<?php
$db = mysql_connect("farrer.csu.edu.au", "keustace", "password");
mysql_select_db("mydatabase", $db);
$result = mysql_query("SELECT * FROM employees", $db);
echo "<table border=1>\n";
echo "<tr><td><b>Name</b></td><td><b>Position</b></td><tr>\n";
while ($myrow = $mysql_fetch_row($result)) {

echo "<tr><td>", $myrow[2], ", ", $myrow[1], "</td></tr>",
$myrow[3], "</td></tr>";

}
echo "</table><BR>";
?>

My code:

8_5_code

The results:

8_5_result

Leave a Reply