- Start with a simple table in the database:
mysql> SELECT * FROM employees; - Create a web page with the following PHP:
<?php
$db = mysql_connect(“farrer.csu.edu.au", “keustace", “password");
mysql_select_db(“mydatabase",$db);
$result = mysql_query("SELECT * FROM employees",$db);
echo "First Name: ", mysql_result($result,0,"first"), "<BR>";
echo "Last Name: ", mysql_result($result,0,"last"), "<BR>";
echo "Address: ", mysql_result($result,0,"address"), "<BR>";
echo "Position: ", mysql_result($result,0,"position"), "<BR>";
?>
My password is included? We look at security later…☺ - 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"><br>
Last name:<INPUT TYPE="Text" NAME="last"><br>
Address:<INPUT TYPE="Text" NAME="address"><br>
Position:<INPUT TYPE="Text" NAME="position"><br>
<INPUT TYPE="Submit" NAME="submit" VALUE="Enter information">
</FORM>
</BODY>
</HTML> - 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("INERT 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";
}
?> - 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></tr>\n";
while ($myrow = mysql_fetch_row($result)) {
echo "<tr><td>", $myrow[2], ", ", $myrow[1], "</td><td>", $myrow[3], "</td></tr>";
}
echo
What this Blog is About
Sunday, May 17, 2009
Exercise 8: PHP and MySQL database access
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment