Create Basic Databases and Integrate with a Website

advertisement
Create Basic Databases and Integrate with a Website – Lesson 3
Combining PHP and MySQL
This lesson presumes you have covered the basics of PHP as well as working with MySQL. Now
you’re ready to make the two interact. So the main purpose of this lesson is to learn how to:
• Connect to MySQL using PHP
• Insert and select data through PHP scripts
To successfully use the PHP functions to talk to MySQL, you must have MySQL running at a location
at which your web server can connect. This does not necessarily mean the same machine as your
web server. You also must have created a user (with a password), and you must know the name of
the database to which you want to connect. WAMPServer should have solved most of these problems
for you, and I could also setup an account on your domain.
When using WAMPServer on localhost, the username will be root with no password. When using
your domain the database is db.username.cessnock-ict.net, with the username being your usual
username and a password of ‘student1’
Connecting to MySQL
The mysql_connect() function is the first function you must call when using a PHP script to connect
to a MySQL database. The basic syntax for the connection is:
msql_connect( ‘hostname’, ‘username’, ‘password’);
This function returns a connection index (or pointer) if the connection is successful, or returns false if
it fails for any reason. So to use it properly you need to store the returning index/pointer in a variable.
For example:
$connection = msql_connect( ‘hostname’, ‘username’, ‘password’);
You would then be able to test the connection, which we will cover shortly, but first let’s see if we can
connect on our localhost, then close the connection.
Closing a connection
The connection normally closes when the script finishes executing. But if you explicitly want to close a
connection, simply use the mysql_close() function at the end of the script. Using the example above,
the syntax would be:
mysql_close($connection)
Your script will still run if you do not include this command but too many open MySQL connections
can cause problems for a web host. It is good practice to always include this line once you have
issued all your commands to the database, to keep the server running well.
Test the localhost connection
Create the script below to open a connection using localhost. Remember you will need Apache and
MySQL running as a background process.
<?php
$conn = mysql_connect("localhost", "root", "");
echo $conn;
mysql_close($conn);
?>
Create a folder C:\wamp\www\mydatabase and save the code above as connect.php in that folder.
FILE=PHPSQL Tutorial - part 1.docx by Greg Tisdell, updated on 7 October 2012
1
Apache sees the C:\wamp\www\ directory as the root directory of your web server e.g. http://localhost/
(or http://127.0.0.1/). Since the www folder represents the root directory of your local web server,
/mydatabase runs below that root folder. The full address of the file’s location would be:
http://localhost/mydatabase/connect.php
If you were to use the C:\Data directory from the last lesson, Apache would not know how to load the
file. Apache would need to be configured to use any other folders, since that is a distraction we’ll just
use the C:\wamp\www\mydatabase folder it already knows about.
To access the script, open a browser and enter the URL localhost/mydatabase/connect.php
When the script executes you should get a response like:
Resource id #1
If the connection is unsuccessful you will get an error message, otherwise you get the message
above. For the time being, just accept the output until we learn how to extract information from the
connection object. Just know that all is good and right with the world if we get a Resource id #.
Selecting the Database
After you have connected to the MySQL host (server) you must then select (USE) the database. This
must be a database that your username has access to. The function is mysql_select_db() and has
the syntax
mysql_select_db( database_name, connection_index )
So if we had were using our Car_Sales database and used the connection index from the example
above, the command would be:
mysql_select_db( ‘Car_Sales’, $conn );
Once again there is the possibility that the function will fail. To take this into account and give us some
indication on where our script fails we could add the die() function. The function takes a string to be
printed to the browser. The better command would be:
@mysql_select_db(‘Car_Sales’, $conn) or die( "Unable to select Car_Sales database");
Do you notice the @ symbol at the beginning of the line? The @ symbol will suppress any output from
the command, other than what we explicitly send – as in the die(“…”) command. If the selection of the
database fails then the output in the browser will be:
Unable to select Car_Sales database
This extra 'or die' part is good to use as it provides a little error control, but it is not essential. Edit the
connect.php file to include selecting the Car_Sales database. Make the following changes:
<?php
$conn = mysql_connect("localhost", "root", "");
echo $conn;
@mysql_select_db('Car_Sales', $conn) or die( "Unable to select Car_Sales database");
mysql_close($conn);
?>
Save the code and test it again. You shouldn’t see any changes, unless the script fails.
So now you know how to open a connection and select a database! Easy isn’t it…
FILE=PHPSQL Tutorial - part 1.docx by Greg Tisdell, updated on 7 October 2012
2
Executing SQL Commands
Now you have connected to the server and selected the database you want to work with, you can
begin executing commands on the server with the mysql_query() function. The general syntax is:
mysql_query( ‘sql_query_string’, connection_index);
There are two ways of executing a command. One is to just enter the command in the
‘sql_query_string’. This way is used if there will be no results from the operation. The other way is to
define the command as a variable. This will set the variable with the results of the operation. The
second method would look like this:
mysql_query($query, $conn);
The useful thing about using this form of the command is that you can just repeat the same command
over and over again without learning new ones. All you need to do is to change the variable.
Insert an Employee
Recall the Car_Sales database, created in the last lesson, has two tables - Vehicles and Employees.
We are going to add another Employee to the table, but in a script. If we were entering information
directly in MySQL, we would use the INSERT command like:
INSERT INTO Employees
(EmployeeID, Last_Name, First_Name, Position, Salary, Phone)
VALUES
(1006, 'Blogs', 'Joe', 'Sales Rep', 30000, '612 4845 6666'),
Now we are going to use the SQL command above, but store it in a variable called $query, then use
it. But we also would like some indication on whether the command executed properly or it failed in
some way. The mysql_query() function also returns true or false reflecting the success or not of the
operation. We can use that to build some feedback and error control into the script.
Modify the connect.php file and make the following changes.
<?php
$conn = mysql_connect("localhost", "root", "");
@mysql_select_db('Car_Sales', $conn) or die( "Unable to select Car_Sales database");
$query = "INSERT INTO Employees(EmployeeID, Last_Name, First_Name, Position, Salary, Phone)
VALUES (1006, 'Blogs', 'Joe', 'Sales Rep', 30000, '612 4845 6666')";
if(mysql_query($query, $conn)){
echo "Record added successfully!";
}else{
echo "Something went wrong with adding the record!";
}
mysql_close($conn);
?>
Save the file as insert_employee.php and run it. It should provide the “Record added successfully!”
output.
Run the file again (hit refresh) and it should fail. Why? Because you can only have 1 record with a
unique primary key. It’s important to remember you have to take into account all the normal
Relational Database issues, as well as writing the script.
FILE=PHPSQL Tutorial - part 1.docx by Greg Tisdell, updated on 7 October 2012
3
Using Replaceable Variables
The way we have the initial connection setup is not satisfactory. It would be more efficient and flexible
(from a programming point of view) to initialise the connect parts in separate variables before we try to
connect. Using this approach we can change the host, username, password in one place. Far easier
to edit and make the code transportable.
Make the following changes, adding variables while also adding another employee.
<?php
$host = "localhost";
$username = "root";
$password = "";
$database = "Car_Sales";
$conn = mysql_connect($host, $username, $password);
@mysql_select_db($database, $conn) or die( "Unable to select $database database");
$query = "INSERT INTO Employees(EmployeeID, Last_Name, First_Name, Position, Salary, Phone)
VALUES (1007, 'Johns', 'Johno', 'Sales Rep', 30000, '612 4845 7777')";
if(mysql_query($query, $conn)){
echo "Record added successfully!";
}else{
echo "Something went wrong with adding the record!";
}
mysql_close($conn);
?>
Save the file and run it. It should once again provide the “Record added successfully!” output.
Error Messages
When working on a database through a script on a web server, there are a number of possible
sources of errors. But there is a useful function that can help identify the nature of MySQL related
errors. The mysql_error() function will output the last error report when something goes wrong.
Include this function in a location where you want to know what went wrong. Let’s use the following
example and modify the last echo statement:
if(mysql_query($query, $conn)){
echo "Record added successfully!";
}else{
echo "Something went wrong. MySQL reports: <b>", mysql_error(), "</b>";
}
Save and run the file. It should fail because there is already an entry with primary key ‘1007’. The
output generated should reflect the type of error that you would receive if you were working directly in
MySQL. An error message such as:
Something went wrong. MySQL reports: Duplicate entry '1007' for key 1
Adding the mysql_error() function to output messages can be a useful debugging method.
Adding a Record from a Form
We are going to expand our insert_employee.php script to take input from a form. So we need an
HTML form with the following parts:
FILE=PHPSQL Tutorial - part 1.docx by Greg Tisdell, updated on 7 October 2012
4
Action: The form’s action property would be the insert_employee.php script
Fields: The form should contain:
• First Name
• Last Name
• Position
• Salary
• Phone number
Should we include the EmployeeID field in our set of available entries? Well our original definition of
the Employees table stated
CREATE TABLE Employees(
EmployeeID INT NOT NULL PRIMARY KEY …
It does not have the AUTO_INCREMENT option, so YES we need to provide a key. Our first draft of
the form and script will be a little rough in that regard, but we can improve on it later. Create the Add
Employee Form as indicated below.
<html><head>
<title>Add Employee</title>
</head>
<body>
<h2>Add Employee Form</h2>
<form method="post" action="insert_employee.php">
<table width="450" border="0">
<tr>
<td width="150">Employee ID</td>
<td width="300"><input type="text" name="EmployeeID" /> </td>
</tr>
<tr>
<td>First Name </td>
<td><input type="text" name="FirstName" /></td>
</tr>
<tr>
<td>Last Name </td>
<td><input type="text" name="LastName" /></td>
</tr>
<tr>
<td>Position</td>
<td><input type="text" name="Position" /></td>
</tr>
<tr>
<td>Salary</td>
<td><input type="text" name="Salary" /></td>
</tr>
<tr>
<td>Phone number </td>
<td><input type="text" name="Phone" /></td>
</tr>
<tr>
<td><input type="reset" name="Reset" value="Cancel" /></td>
<td><input type="submit" name="Submit" value="Add Employee Entry" /></td>
</tr>
</table>
</form>
<p> </p>
</body>
</html>
FILE=PHPSQL Tutorial - part 1.docx by Greg Tisdell, updated on 7 October 2012
5
Save the document as add_employee.htm in the same directory as insert_employee.php. The form
should look similar to the image below.
Now we have a form, we need to edit the insert_employee.php file to accept the data posted to it.
There are a number of changes that need to be made. For instance we need to:
1. extract all the information from the form
2. then we need to assemble a SQL query that uses those extracted values
3. execute the SQL command
4. if the addition of a new record was successful, or a failure, produce some feedback
accordingly.
Modify the insert_employee.php file as indicated below
<?php
$host = "localhost";
$username = "root";
$password = "";
$database = "Car_Sales";
// extract the values from the form
$employeeid = $_POST['EmployeeID'];
$firstName = $_POST['FirstName'];
$lastName = $_POST['LastName'];
$position
= $_POST['Position'];
$salary
= $_POST['Salary'];
$phone
= $_POST['Phone'];
// assemble the sql query string to insert a record
$query = "INSERT INTO Employees(EmployeeID, Last_Name, First_Name, Position, Salary, Phone)
VALUES ($EmployeeID, '$lastName', '$firstName', '$position', $salary, '$phone')";
// open a connection and select the database
$conn = mysql_connect($host, $username, $password);
@mysql_select_db($database, $conn) or die( "Unable to select $database database");
// add the record
if(mysql_query($query, $conn)){
echo "Record added successfully!";
}else{
echo "Something went wrong. MySQL reports: <b>", mysql_error(), "</b>";
}
// reuse the previous form
include("add_employee.htm");
mysql_close($conn);
?>
Save the code above, and load your form in the browser.
FILE=PHPSQL Tutorial - part 1.docx by Greg Tisdell, updated on 7 October 2012
6
You may have noticed that we have not included basic checking, such as the data being submitted by
a post compared to a get. At this stage the focus is on the fundamental components that make it
work.
Enter the details as indicated by the adjacent form,
and submit the form to the script.
If the addition (INSERTion) of the record works as it
should, you would be returned to the form. The form
should indicate whether the addition was successful
or not.
Add another entry as indicated:
After submitting the new entry adjacent, you should
once again be confirmed as having added a record,
and presented with the form ready to go again.
Now we have couple more entries it might be time to see what is in the Employees table.
Viewing Records
Recall the basic SELECT statement that you use in a MySQL query to view all the records in the
Employees table.
SELECT * FROM Employees
We will still use this basic SQL command in a script to select all the records in the Employees table,
but just as before, we’ll assign it to a variable first.
The output from this command, when executed, will return heaps of stuff (technical term), so should
be assigned to a variable that we can work with.
$query = "SELECT * FROM Employees";
$result = mysql_query($query, $conn);
In this case the whole contents of the database is now contained in a special array with the name
$result. The $result will be in simplistic terms, a two-dimensional array. As a consequence, before
you can output this data you must extract each individual record into a separate variable (which is a
single array in itself).
FILE=PHPSQL Tutorial - part 1.docx by Greg Tisdell, updated on 7 October 2012
7
The command to extract a single array (row of columns that amount to a single record), we use the
mysql_fetch_array() function. The syntax is:
$recordArray = mysql_fetch_array($result)
Each time the mysql_fetch_array() function is called, it moves an internal pointer to the next record.
So next time you make the same function call, you get the next record – till there are none to fetch.
There are other ways of extracting specific data from the returning result, but this is one of the
simplest.
Accessing Individual Columns
As each row (record) is extracted, it is still stored as an array. There are two ways this data can be
extracted, first using the subscript (index) method of normal arrays, or as an associative array using
column names. Compare the two examples.
$recordArray[0]
$recordArray[EmployeeID]
Counting Rows
One useful piece of information to extract (apart from the actual column entries) is how many
database rows were returned. To know how many rows (records) are returned, use the
mysql_numrows() function. The general syntax would be:
$rows = mysql_numrows($result);
This will set the value of $rows to be the number of rows stored in $result (the output you got from the
database). This can then be used in a loop to get all the data and output it on the screen.
Let’s create a script that extracts all the Employee details and displays it in an HTML table. But first
we’ll just test to see how many records are returned.
<title>Employee Details</title>
</head>
<body>
<h2>Employee Details</h2>
<?php
$host = "localhost";
$username = "root";
$password = "";
$database = "Car_Sales";
// assemble the sql query string to insert a record
$query = "SELECT * FROM Employees";
// open a connection and select the database
$conn = mysql_connect($host, $username, $password);
@mysql_select_db($database, $conn) or die( "Unable to select $database database");
// Execute the sql query
if($result = mysql_query($query, $conn)){
$rows = mysql_numrows($result);
echo "<p>There are $rows employees in the system</p>";
}else{
echo "Something went wrong. MySQL reports: <b>", mysql_error(), "</b>";
}
mysql_close($conn);
?>
FILE=PHPSQL Tutorial - part 1.docx by Greg Tisdell, updated on 7 October 2012
8
Save the code above as show_employees.php and run it. The result should be as show below…
Employee Details
There are 9 employees in the system
Since we have made a successful connection, and have determined there are records to display, let’s
edit the script to display the records. We’ll need to add some more HTML to display the records neatly
in a tabular format.
<html><head><title>Employee Details</title></head><body>
<h2>Employee Details</h2>
<?php
$host = "localhost";
$username = "root";
$password = "";
$database = "Car_Sales";
$query = "SELECT * FROM Employees"; // assemble the sql query string to get all records
// open a connection and select the database
$conn = mysql_connect($host, $username, $password);
@mysql_select_db($database, $conn) or die( "Unable to select $database database");
// Execute the sql query
if($result = mysql_query($query, $conn)){
$rows = mysql_numrows($result);
echo "<p>There are $rows employees in the system</p>";
?>
<table border="1">
<tr>
<td>Employeed ID</td>
<td>First Name</td>
<td>Last Name</td>
<td>Position</td>
<td>Salary</td>
<td>Contact Number</td>
</tr>
<?php
$i = 0;
while($i < $rows){
$recordArray = mysql_fetch_array($result); // fetch and display a record
echo "<tr>
<td>$recordArray[0]</td>
<td>$recordArray[2]</td>
<td>$recordArray[1]</td>
<td>$recordArray[3]</td>
<td>$recordArray[4]</td>
<td>$recordArray[5]</td>
</tr>";
$i++;
}
}else{
echo "Something went wrong. MySQL reports: <b>", mysql_error(), "</b>";
}
?>
</table>
<?php
mysql_close($conn);
?>
</body></html>
FILE=PHPSQL Tutorial - part 1.docx by Greg Tisdell, updated on 7 October 2012
9
Save the changes above and run it. You should be output like the image below.
Notice in this example the use of the index version of accessing the column (field) contents. That of
$recordArray[1]
Using this method is simple but harder to keep track of which column with which you are dealing. As
an example, notice that the Last Name and First Name are not in the same order as the SQL
statement. To make life a little easier we could modify the code to use column names instead. Make
the following modifications to the code…
echo "<tr>
<td>$recordArray[EmployeeID]</td>
<td>$recordArray[First_Name]</td>
<td>$recordArray[Last_Name]</td>
<td>$recordArray[Position]</td>
<td>$recordArray[Salary]</td>
<td>$recordArray[Phone]</td>
</tr>";
Save the changes and run it again. The output should be the same, just easier to follow each entry in
the associative array.
Getting the correct key
In our current form that adds an Employee, the user is expected to know what the next ID field should
be, or at least that it should even be a number. It would be more desirable if the form already
contained the next available ID number. A number that is both sequentially next and valid. How could
this be achieved?
FILE=PHPSQL Tutorial - part 1.docx by Greg Tisdell, updated on 7 October 2012
10
If a search of the current highest entry (MAX) in the EmployeeID column was known, we could simply
increment it. We would need to do this before displaying the form, and the form would need to use the
incremented value in the appropriate place, so it too would need to be modified.
So our plan is to:
1. Get the current highest value in the EmployeeID column of the Employees table
2. Increment the returning value, therefore giving us the next likely number
3. Display the Add Employee Form with the next number already showing
Create new_employee.php
The new_employee.php file will be the working engine of our new version of adding new employees.
The script will perform the tasks outlined in our plan above.
Since we already have the HTML form that accepts new entries, we could modify it slightly and simply
include() it in our new_employee.php script. Load the add_employee.htm file in your editor and
make the small change as indicated.
<tr>
<td width="150">Employee ID</td>
<td width="312">
<input type="text" name="EmployeeID" value="<?= $nextID ?>" />
</td>
</tr>
Save the add_employee.htm file.
Create a new file, called new_employee.php, that will present the form with the correct $nextID
<?php
$host = "localhost";
$username = "root";
$password = "";
$database = "Car_Sales";
// assemble the sql query string
$query = "SELECT MAX(EmployeeID) AS LastID FROM Employees";
// open a connection and select the database
$conn = mysql_connect($host, $username, $password);
@mysql_select_db($database, $conn) or die( "Unable to select $database database");
// get the LastID, calculate the nextID and display the form
if($result = mysql_query($query, $conn)){
$row = mysql_fetch_array($result);
$nextID = $row[LastID];
$nextID++;
include("add_employee.htm");
}else{
echo "Something went wrong. MySQL reports: <b>", mysql_error(), "</b>";
}
mysql_close($conn);
?>
Save the file as new_employee.php and run it. The Add Employee Form should appear with the next
available EmployeeID already entered.
FILE=PHPSQL Tutorial - part 1.docx by Greg Tisdell, updated on 7 October 2012
11
There is another change as a consequence of our script. When the add_employee.htm file is included
by the insert_employee.php file, there will not be any nextID to be entered once the scripts have
executed. To fix the problem, edit the insert_employee.php file to call new_employee.php instead. For
example, the last couple of lines of the insert_employee.php file should now be:
// close the connection and execute the new_employee.php script
mysql_close($conn);
include("new_employee.php");
?>
Make the changes above and save the insert_employee.php file. Test out your new version by
running the new_employee.php script and adding some fictitious employees of your own.
Deleting Employees
While we’re adding some employees of our own making, it would be a worthwhile activity to be able to
display all the employees and simply delete the entries we no longer require. We already have a
script that displays all the employees, so we could modify that to achieve our aim.
There are many ways we could go about this task. Just to show we can also use the GET method to
execute some scripting goals, we will:
1. Create a delete_employee.php script that will:
a. Determine the EmployeeID from a query string as part of a GET
b. Delete the record for the employee
c. Call the show_employees.php script
2. Modify the show_employees.php script would need to include a link that calls the
delete_employee.php script, passing a query string in the URL.
Create delete_employee.php file which will achieve the goals above. You will notice that most of the
code is the same as the insert_employee.php, with changes to the SQL query string and how the
$employeeid is obtained. The lines of code that are different are highlighted.
<?php
$host = "localhost";
$username = "root";
$password = "";
$database = "Car_Sales";
// extract the value from the query string
$employeeid = $_GET['EmployeeID'];
// assemble the sql query string to delete a record
$query = "DELETE FROM Employees WHERE EmployeeID = $employeeid";
// open a connection and select the database
$conn = mysql_connect($host, $username, $password);
@mysql_select_db($database, $conn) or die( "Unable to select $database database");
// delete the record
if(mysql_query($query, $conn)){
echo "Record deleted successfully!";
}else{
echo "Something went wrong. MySQL reports: <b>", mysql_error(), "</b>";
}
// close the connection and call the show_employees.php script
mysql_close($conn);
include("show_employees.php");
?>
Save the code above and make the following changes to the show_employees.php script.
FILE=PHPSQL Tutorial - part 1.docx by Greg Tisdell, updated on 7 October 2012
12
<table border="1">
<tr>
<td>Employeed ID</td>
<td>First Name</td>
<td>Last Name</td>
<td>Position</td>
<td>Salary</td>
<td>Contact Number</td>
<td>Admin Options</td>
</tr>
<?
while($i < $rows){
// fetch a record
$recordArray = mysql_fetch_array($result);
echo "<tr>
<td>$recordArray[EmployeeID]</td>
<td>$recordArray[First_Name]</td>
<td>$recordArray[Last_Name]</td>
<td>$recordArray[Position]</td>
<td>$recordArray[Salary]</td>
<td>$recordArray[Phone]</td>
<td>
<a href='delete_employee.php?EmployeeID=$recordArray[EmployeeID]'>Delete</a>
</td>
</tr>";
$i++;
}
}else{
echo "Something went wrong. MySQL reports: <b>", mysql_error(), "</b>";
}
?>
</table>
Save the changes above and run the show_employees.php script. You should be able to delete a
record by clicking on the DELETE link, and it all should happen very quick! After deleting a record,
take notice of the query string in the URL – that’s what makes it a GET and not a POST request and
why we can makes things happen from a simple link.
Now we have a set of scripts that can ADD and DELETE, but does not allow for EDIT employees.
Editing Employees
To be able to edit an employee’s details we need a form that displays the details, and also submits to
an update script. We could do them separately or we could do it all in a single script. In any case we
can recycle the add_employee.htm file to save on typing. We will do it using 3 files simply to make
each smaller.
The sequence of events will be:
• edit_employee.php is called as a GET request from show_employees.php
• edit_employee.htm is displayed with details extracted from the database, the form submits
to the update_employee.php script
• update_employee.php extracts the details from the POST and updates the database,
returning to show_employees.php
Copy the add_employee.htm file to one called edit_employee.htm. We are going to make the
following modifications to the edit_employee.htm file.
FILE=PHPSQL Tutorial - part 1.docx by Greg Tisdell, updated on 7 October 2012
13
<title>Edit Employee</title>
</head>
<body>
<h2>Edit Employee Form</h2>
<form method="post" action="update_employee.php">
<table width="450" border="0">
<tr>
<td width="150">Employee ID</td>
<td width="312"><input type="hidden" name="EmployeeID" value="<?= $employeeid ?>"/>
<?= $employeeid ?> </td>
</tr>
<tr>
<td>First Name </td>
<td><input type="text" name="FirstName" value="<?= $firstName ?>"/></td>
</tr>
<tr>
<td>Last Name </td>
<td><input type="text" name="LastName" value="<?= $lastName ?>" /></td>
</tr>
<tr>
<td>Position</td>
<td><input type="text" name="Position" value="<?= $position ?>" /></td>
</tr>
<tr>
<td>Salary</td>
<td><input type="text" name="Salary" value="<?= $salary ?>" /></td>
</tr>
<tr>
<td>Phone number </td>
<td><input type="text" name="Phone" value="<?= $phone ?>" /></td>
</tr>
<tr>
<td><input type="reset" name="Reset" value="Reset" /></td>
<td><input type="submit" name="Submit" value="Update Employee Entry" /></td>
</tr>
</table>
<input type="button" name="Cancel" value="Cancel and Return"
onclick="javascript:window.history.go(-1);" />
</form>
Save the changes to edit_employee.htm. Notice that we are using a hidden text field rather than
having the EmployeeID displayed in a normal ‘text’ input field. This is to prevent the user accidentally
changing the EmployeeID which would make the whole process collapse. Also, we have added a
“Cancel and Return” button to allow the whole operation to be cancelled.
Now create the script that will extract the employee’s details and present them in the form above.
<?php
$host = "localhost";
$username = "root";
$password = "";
$database = "Car_Sales";
// extract the employeeid from the GET request
$employeeid = $_GET['EmployeeID'];
FILE=PHPSQL Tutorial - part 1.docx by Greg Tisdell, updated on 7 October 2012
14
// assemble the sql query string to extract a record
$query = "SELECT * FROM Employees WHERE EmployeeID = $employeeid";
// open a connection and select the database
$conn = mysql_connect($host, $username, $password);
@mysql_select_db($database, $conn) or die( "Unable to select $database database");
// Execute the sql query and extract the column values
if($result = mysql_query($query, $conn)){
$record = mysql_fetch_array($result);
$firstName = $record['First_Name'];
$lastName = $record['Last_Name'];
$position = $record['Position'];
$salary = $record['Salary'];
$phone = $record['Phone'];
}else{
echo "Something went wrong. MySQL reports: <b>", mysql_error(), "</b>";
}
mysql_close($conn);
include("edit_employee.htm");
?>
Save the code above as edit_employee.php. The next step is to create the script that actually
updates the database.
Create the code below that actually updates the database, then passes control back to
show_employees.php. It passes control – not just includes the file.
<?php
$host = "localhost";
$username = "root";
$password = "";
$database = "Car_Sales";
// extract the values from the form
$employeeid = $_POST['EmployeeID'];
$firstName = $_POST['FirstName'];
$lastName = $_POST['LastName'];
$position = $_POST['Position'];
$salary = $_POST['Salary'];
$phone = $_POST['Phone'];
// assemble the sql query string
$query = "UPDATE Employees SET
First_Name = '$firstName',
Last_Name = '$lastName',
Position = '$position',
Salary = '$salary',
Phone = '$phone'
WHERE EmployeeId = '$employeeid'";
// open a connection and select the database
$conn = mysql_connect($host, $username, $password);
@mysql_select_db($database, $conn) or die( "Unable to select $database database");
// update the record
if(mysql_query($query, $conn)){
mysql_close($conn);
FILE=PHPSQL Tutorial - part 1.docx by Greg Tisdell, updated on 7 October 2012
15
header("Location: show_employees.php");
exit;
}else{
echo "Something went wrong. MySQL reports: <b>", mysql_error(), "</b>";
}
?>
Save the code as update_employee.php. There is one small change we should make to the
show_employees.php before testing it out. Load the show_employees.php and make the
highlighted changes.
<a href="new_employee.php">Add New Employee</a><br />
<table border="1">
<tr>
<td>Employeed ID</td>
<td>First Name</td>
<td>Last Name</td>
<td>Position</td>
<td>Salary</td>
<td>Contact Number</td>
<td>Admin Options</td>
</tr>
<?
while($i < $rows){
// fetch a record
$recordArray = mysql_fetch_array($result);
echo "<tr>
<td>$recordArray[EmployeeID]</td>
<td>$recordArray[First_Name]</td>
<td>$recordArray[Last_Name]</td>
<td>$recordArray[Position]</td>
<td align='right'>$recordArray[Salary]</td>
<td>$recordArray[Phone]</td>
<td><a href='delete_employee.php?EmployeeID=$recordArray[EmployeeID]'>Delete</a>
<a href='edit_employee.php?EmployeeID=$recordArray[EmployeeID]'>Edit</a>
</td>
</tr>";
Save the changes above and run the show_employees.php script in the browser. The output should
look the same as it did before, but with Add, Edit and Delete options. To launch the Edit process,
simply click the link!
Now let’s see if you can use and extend the knowledge in this tutorial with a challenge or two.
FILE=PHPSQL Tutorial - part 1.docx by Greg Tisdell, updated on 7 October 2012
16
Exercises
Challenge 1
Create a script that shows all sold vehicles. Refer to the last tutorial if you can’t recall the SQL
statement.
Challenge 2
Using the script in Challenge 1, add the full name of the employee that sold the vehicle
Challenge 3
Create a script that displays the Make, Model, Rego_no, Cost_price and Sale_Price columns of all
unsold vehicles.
Challenge 4
Add a ‘Sold’ link to the output, that when clicked, will launch a form to enter the Vehicle sold details for
a particular Rego number. E. g. ‘sold_vehicle.php?Rego_No=$rego‘
Challenge 5
Create a script (sold_vehicle.php) with a form that can be used to enter sold vehicles. The form
should display the Make, Model, Rego_no and Sale_Price - the Sale_Price should be editable. The
script should use the Rego_no passed as a GET query string i.e. from the link in Challenge 4.
Challenge 6
Modify the form in Challenge 5 to include a dropdown list (HTML select) that contains all the
Employee’s names, with their EmployeeID as the value. For example, for each employee you would
add an option to the select like this:
<select name=”Employee” >
** loop code**
<option value=’<?= $employeeId ?>’ > <? echo “ $firstName $lastName”; ?> </option>
** end loop code**
</select>
To achieve this, it means there will be two separate SQL statements executed. First you could find all
the employees, and save that information in an array. Then find the Vehicle information.
Challenge 7
Create a script that will UPDATE the Vehicles table to indicate a vehicle has been sold. This will be
the script that the form, created in Challenge 5, is submitted to.
To achieve make this possible it means the EmployeeID field should contain a valid EmployeeID, an
updated Sale_Price, and use the Rego_No in the WHERE clause of the SQL query.
Challenge 8
Modify the scripts in this lesson to make then more manageable. This means cut the references to the
host, database, usernames, connecting etc. into a separate file called db_connect.php and include
this file at the top of each script that used the database.
FILE=PHPSQL Tutorial - part 1.docx by Greg Tisdell, updated on 7 October 2012
17
Download