Friday, June 12, 2009

Exercise 8.4 - PHP and MySQL database access

Question 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("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";
}
?>

Created the web page with the above PHP. The mysql_connect function needed to be changed to my local credentials as follows:

$db = mysql_connect("localhost","root","");

Clicked on Enter Information button on the form page from Question 3 but it didn't work and I got the following errors:

Notice: Undefined variable: first in c:\instantrails\www\php\add_record.php on line 3
Notice: Undefined variable: last in c:\instantrails\www\php\add_record.php on line 3
Notice: Undefined variable: address in c:\instantrails\www\php\add_record.php on line 3
Notice: Undefined variable: position in c:\instantrails\www\php\add_record.php on line 3

To access the form variables I need to use $_POST so I have used the following code in the submit.php file.

$result = mysql_query("INSERT INTO employees (first,last,address,position) VALUES ('$_POST[first]','$_POST[last]','$_POST[address]','$_POST[position]')");

Also the sample code above had INERT instead of INSERT which I have also changed.

The results of the page are now as follows:

Thank you! Your information has been entered.

My employees table now has the following records:

mysql> select * from employees;

+-------+--------+------------------+-------------------+
| first | last | address | position |
+-------+--------+------------------+-------------------+
| Fred | Nerk | 88 Nerk Street | Managing Director |
| Karen | Carter | 123 Test Street | Programmer |
| John | Smith | 666 Jones Street | Director |
+-------+--------+------------------+-------------------+
3 rows in set (0.00 sec)

No comments:

Post a Comment