Creating A CRUD Application With PHP
Creating A CRUD Application With PHP
Creating A CRUD Application With PHP
4. To execute an SQL command, you need to be connected to a database. Because only the MySQL
system is available, you need to connect to it. To connect to the system database, navigate to the
mysql node and from the context menu choose Connect. If a connection does not already exist, the
New Database Connection dialog box appears. The User Name field is by default filled in with root.
In the Password field, enter the root user's password.
The New Database Connection dialog box shows the message "Connection established." Click OK.
A new node named jdbc:mysql://localhost:3306/mysql is added to the Databases tree.
5. Navigate to the jdbc:mysql://localhost:3306/mysql node and from the context menu choose
Execute Command.
An SQL Command window opens. In the SQL Command window, use syntax similar to the
following statement:
6. CREATE USER 'phpuser'@'localhost'
IDENTIFIED BY '!phpuser'
From the context menu, choose Run Statement. If the command is executed successfully, the Status
bar shows the message: "SQL Statement(s) executed successfully". If another message is displayed,
check the syntax and follow the message hints.
Creating the Sample Database
To create the database:
1. Navigate to the MySQL Server at localhost:3306 node and from the context menu choose Create
Database. The Create MySQL Database dialog box appears. Fill in the fields:
○ In the Database Name field, enter wishlist.
○ Switch on the Grant full access to user checkbox and from the drop down list select
phpuser@localhost phpuser @ localhost Click OK.
The "Grant full access to user" function does not always work. If it does not work, connect to
the database as the root user and send the SQL query GRANT ALL ON wishlist.* TO
phpuser@localhost phpuser @ localhost .
2. The New Database Connection dialog box appears.
Establishing Connection to the Sample Database
In the New Database Connection dialog box, fill in the fields:
1. From the Name drop down list, choose MySQL (Connector/J driver)
2. In the Database URL edit box, specify the host, the port, and the database as follows:
jdbc:mysql://localhost:3306/wishlist
3. In the User Name and Password edit boxes, enter the name and the password specified in section
Creating the Owner (User) of the Database (in our example phpuser and !phpuser respectively).
Click OK. The corresponding new connection node is displayed in the Databases tree.
4. (Optional) Now you can delete the default mysql connection by navigating to the
jdbc:mysql://localhost:3306/ node and choosing Disconnect and then Delete from the context
menu.
Designing the Structure of the Sample Database
To arrange and store all the necessary data you need two tables:
• A wishers table for storing names and passwords of registered users
• A wishes table for storing descriptions of wishes
The wishers table contains three fields:
1. id - the unique ID of a wisher. This field is used as the Primary Key
2. name
3. password
4. According to your project setup, the index.php file is already created. If not, create it as
described above.
5. Switch to the Projects window, expand your project node, and double click the
index.php file. The index.php file opens in the main IDE editor area. The file contains a
template for entering HTML and PHP code.
Note: You can ignore warnings from the HTML validator.
Testing index.php
To test the front index.php page of your application:
1. Click the right mouse button on the Sources node and choose Run Project from the
context menu or click the Run Main Project icon on the toolbar if you have set your
project as Main.
2. In the Show wish list of: edit box, enter Tom and click Go. An empty page with the
following URL appears: http://localhost:90/Lesson2/wishlist.php?user=tom. This URL
indicates that your main page works properly.
<?php
/*
*/
?>
</body>
</html>
The PHP code block displays the data that is received through the method GET in the field "user".
This data is transferred from index.php where the name of the wish list owner Tom was entered in
the text field "user". Repeat the steps from Testing index.php to see that wishlist.php works properly.
13.Delete the commented section in the template PHP block. Paste the following code
block where the comments were. This code opens the connection to the database.
14.$con = mysql_connect("localhost", "phpuser", "!phpuser");
15.if (!$con) {
16. die('Could not connect: ' . mysql_error());
17.}
mysql_query("SET NAMES 'utf8'");
The code attempts to open a connection to the database and gives an error message if
there is a failure.
18.Beneath the code to open the connection to the database, in the same PHP block, type
or paste the following code. This code retrieves the ID of the wisher whose wish list was
requested:
19.mysql_select_db("wishlist", $con);
20.$wisher = mysql_query("SELECT ID FROM wishers WHERE
name='".mysql_real_escape_string($_GET["user"])."'");
$wisherID = mysql_result($wisher, 0);
The data is selected from the wishlist database through the $con connection. The
selection criterion is the name received from the index.php as "user".
The syntax of a SELECT SQL statement can be briefly described as follows:
○ After SELECT, specify the fields from which you want to get data. An asterisk (*)
stands for all fields.
○ After FROM clause, specify the name of the table from which the data must be
retrieved.
○ The WHERE clause is optional. Specify the filter conditions in it.
Security Note: The $_GET["user"] parameter is escaped in order to prevent SQL injection attacks.
See Wikipedia on SQL injections and the mysql_real_escape_string documentation. Although in
the context of this tutorial you are not at risk of harmful SQL injections, it is best practice to escape
strings in MySQL queries that would be at risk of such an attack.
21.Above the code to retrieve the ID of the wisher, type or paste the following code. This
code kills the process and displays an error message if the requested wisher is not
found in the database:
22.if (mysql_num_rows($wisher)<1) {
23. die("The person " .$_GET["user"]. " is not found. Please check the spelling
and try again" );
}
This PHP block is now complete. The wishlist.php file now looks like this:
<html>
<?php
if (!$con) {
mysql_select_db("wishlist", $con);
if (mysql_num_rows($wisher)<1) {
die("The person " .$_GET["user"]. " is not found. Please check the
spelling and try again" );
}
$wisherID = mysql_result($wisher, 0);
?>
</body>
</html>
If you test the application and enter an invalid user, the following message appears.
24.Beneath the PHP block, type or paste the following HTML code block. This code opens a
table, specifies the color of its borders (black), and "draws" the table header with the
columns "Item" and "Due Date."
25.<table border="black">
26. <tr>
27. <th>Item</th>
28. <th>Due Date</th>
29. </tr>
</table>
The </table> tag closes the table.
30.Enter the following PHP code block above the closing </table> tag:
31.<?php
$result = mysql_query("SELECT * FROM wishes WHERE wisher_id=". $wisherID);
while($row = mysql_fetch_array($result)) {
32. $desc = $row["description"];
$dueDate = $row["due_date"];
echo "<tr><td>" . strip_tags($desc,'<br><p><h1>')."</td>";
echo "<td>". strip_tags($dueDate)."</td></tr>\n";
}
mysql_close($con);
?>
Within the code:
○ The SELECT query retrieves the wishes with their due dates for the specified
wisher by his ID, which was retrieved in step 4, and stores the wishes and due
dates in an array $result.
○ A loop displays the items of the $result array as rows in the table while the array
is not empty.
○ The <tr></tr> tags form rows, the <td></td> tags form cells within rows,
and \n starts a new line.
○ The strip_tags function removes any html tags from the displayed description
and date. Note that <br>, <p>, and <h1> tags are allowed in the description.
The strip_tags function cannot accept a variable passed as a reference, which is
why the variables $desc and $dueDate are created.
○ The $con connection to the database is closed.
Note: By default, MySQL is configured to be case sensitive. Make sure you type the names of
database fields exactly as they are specified during the database table creation.
Security note: Strip tags from database entries before displaying them in order to prevent cross-site
scripting. Although this is not a risk in the context of this tutorial, it is best practise to always write
code that is free of vulnerabilities.
33.To test the application, run the project as described in section Testing index.php.
11.Below the variables, add an if clause. The parameter of the if clause checks that the
page was requested from itself via the POST method. If not, the further validations are
not performed and the page is shown with empty fields as described above.
12.if ($_SERVER["REQUEST_METHOD"] == "POST") {
13.
}
14.Within the curly braces of the if clause, add another if clause that checks whether
the user has filled in the wisher's name. If the text field "user" is empty, the value of
$userIsEmpty is changed to true.
15.if ($_SERVER["REQUEST_METHOD"] == "POST") {
16.
17.
18. if ($_POST["user"]=="")
19. $userIsEmpty = true;
}
20.Add code that establishes a database connection. If the connection cannot be
established, the MySQL error is sent to the output.
21.if ($_SERVER["REQUEST_METHOD"] == "POST") {
22.
23.
24. if ($_POST["user"]=="") {
25. $userIsEmpty = true;
26. }
27.
28. $con = mysql_connect("localhost", "phpuser", "!phpuser");
29. if (!$con) {
30. die('Could not connect: ' . mysql_error());
31. }
32. mysql_query("SET NAMES 'utf8'");
}
33.Add code that checks whether a user whose name matches the "user" field already
exists. The code does this by trying to find a wisher ID number for a name matching the
name in the "user" field. If such an ID number exists, the value of $userNameIsUnique is
changed to "false."
34.if ($_SERVER["REQUEST_METHOD"] == "POST") {
35.
36. if ($_POST["user"]=="") {
37. $userIsEmpty = true;
38. }
39.
49. if ($_POST["user"]=="") {
50. $userIsEmpty = true;
51. }
52.
if ($_POST["password"]=="")
$passwordIsEmpty = true;
if ($_POST["password2"]=="")
$password2IsEmpty = true;
if ($_POST["password"]!=$_POST["password2"]) {
$passwordIsValid = false;
}
}
60. Complete the if clause by adding code that inserts a new entry into the "wishers" database. The
code checks that the name of the wisher is specified uniquely and that the password is entered and
confirmed validly. If the conditions are met, the code takes the "user" and "password" values from
the HTML form and inserts them into the Name and Password columns, respectively, of a new row
in the wishers database. After creating the row, the code closes the database connection and redirects
the application to the page editWishList.php.
61.if ($_SERVER["REQUEST_METHOD"] == "POST") {
62.
63. if ($_POST["user"]=="") {
64. $userIsEmpty = true;
65. }
66.
72.
if ($_POST["password"]=="")
$passwordIsEmpty = true;
if ($_POST["password2"]=="")
$password2IsEmpty = true;
if ($_POST["password"]!=$_POST["password2"]) {
$passwordIsValid = false;
}
mysql_select_db("wishlist", $con);
mysql_query("INSERT wishers (name, password) VALUES ('".
$_POST["user"]."', '".$_POST["password"]."')");
mysql_close($con);
header('Location: editWishList.php' );
exit;
}
}
Displaying Error Messages in the Input Form
Now you implement the display of error messages when the entered data is invalid. The implementation is
based on the validations and changes to the values of the boolean variables described in Validating Data and
Adding It to the Database.
1. Enter the following PHP code block inside the HTML input form, below the wisher's
name input:
2. Welcome!<br>
<form action="createNewWisher.php" method="POST">
Your name: <input type="text" name="user"/><br/>
3.
4.
5. <?php
6. if ($userIsEmpty) {
7. echo ("Enter your name, please!");
8. echo ("<br/>");
9. }
10. if (!$userNameIsUnique) {
11. echo ("The person already exists. Please check the spelling and try
again");
12. echo ("<br/");
13. }
?>
14.Enter the following PHP code block inside the HTML input form below the code for the
password input:
15.Password: <input type="password" name="password"/><br/>
16.
17.<?php
18. if ($passwordIsEmpty) {
19. echo ("Enter the password, please!");
20. echo ("<br/>");
21. }
?>
22.Enter the following PHP code blocks inside the HTML input form below the code for
password confirmation:
23.Please confirm your password: <input type="password" name="password2"/><br/>
24.
25.
26.
27.<?php
28. if ($password2IsEmpty) {
29. echo ("Confirm your password, please");
30. echo ("<br/>");
31. }
32. if (!$password2IsEmpty && !$passwordIsValid) {
33. echo ("The passwords do not match!");
34. echo ("<br/");
35. }
?>
3. Leave only the Your name field empty and click Register. An error message displays.
4. Enter the name of a registered wisher, for example, Tom in the Your name field, fill in
the other fields correctly, and click Register. An error message displays.
5. Fill in the Password and Please confirm your password fields with different values and
click Register. An error message displays.
6. Enter Bob in the Your name field, specify the same password in both password fields
and click Register. The page that opens is empty but the redirection passed correctly as
the URL ends with editWishList.php:
7. To check that the data is stored in the database, navigate to wishers on the Services
window below the wislist1 node and from the context menu choose View Data
<?php
class WishDB {
}
?>
The object (or "instance") of the WishDB class is stored in the $instance variable. In the code above, it is
declared null. You also declare database configuration variables for storing the name and password of the
database owner (user), the name of the database, and the database host. All these variable declarations are
"private," meaning that the initial values in the declarations cannot be accessed from outside the WishDB
class (See php.net).
Instantiating the WishDB class
For other PHP files to use functions in the WishDB class, these PHP files need to call a function that creates
an object of ("instantiates") the WishDB class. WishDB is designed as a singleton class, meaning that only
one instance of the class is in existance at any one time. It is therefore useful to prevent any external
instantiation of WishDB, which could create duplicate instances.
Inside the WishDB class, type or paste the following code:
//This method must be static, and must return an instance of the object if the object
//does not already exist.
public static function getInstance() {
if (!self::$instance instanceof self) {
self::$instance = new self;
}
return self::$instance;
}
// The clone and wakeup methods prevents external instantiation of copies of the
Singleton class,
// thus eliminating the possibility of duplicate objects.
public function __clone() {
trigger_error('Clone is not allowed.', E_USER_ERROR);
}
public function __wakeup() {
trigger_error('Deserializing is not allowed.', E_USER_ERROR);
}
The getInstance function is "public" and "static." "Public" means that it can be freely accessed from
outside the class. "Static" means that the function is available even when the class has not been instantiated.
As the getInstance function is called to instantiate the class, it must be static.
The double-colon (::), called the Scope Resolution Operator, and the self keyword are used to access static
functions. Self is used from within the class definition to refer to the class itself. When the double-colon is
used from outside the class definition, the name of the class is used instead of self. See php.net on the
Scope Resolution Operator.
Adding a Constructor to the WishDB Class
A class can contain a special method known as a 'constructor' which is automatically processed whenever an
instance of that class is created. In this tutorial, you add a constructor to WishDB that connects to the
database whenever WishDB is instantiated.
Add the following code to WishDB:
// private constructor
private function __construct() {
$this->con = mysql_connect($this->dbHost, $this->user, $this->pass)
or die ("Could not connect to db: " . mysql_error());
mysql_query("SET NAMES 'utf8'");
mysql_select_db($this->dbName, $this->con)
or die ("Could not select db: " . mysql_error());
}
Note the use of the pseudovariable $this instead of the variables $con, $dbHost, $user, or $pass. The
pseudovariable $this is used when a method is called from within an object context. It refers to the value of
a variable within that object.
Functions in the WishDB Class
In this lesson you will implement the following functions of the WishDB class:
• get_wisher_id_by_name for retrieving the id of a wisher based on the wisher's name
• get_wishes_by_wisher_id for retrieving a list of wishes of the wisher with a specific id
• create_wisher for adding a new wisher record to the table wishers
Function get_wisher_id_by_name
The function requires the name of a wisher as the input parameter and returns the wisher's id.
Type or paste the following function into the WishDB class, after the WishDB function:
Security Note: The $name string is escaped in order to prevent SQL injection attacks. See Wikipedia on
SQL injections and the mysql_real_escape_string documentation. Although in the context of this tutorial
you are not at risk of harmful SQL injections, it is best practice to escape strings in MySQL queries that
would be at risk of such an attack.
Function get_wishes_by_wisher_id
The function requires the id of a wisher as the input parameter and returns the wishes registered for the
wisher.
Enter the following code block:
Function create_wisher
The function creates a new record in the wishers table. The function requires the name and password of a
new wisher as the input parameters and does not return any data.
Enter the following code block:
1. At the top of the <?php ?> block, enter the following line to enable the use of the
db.php file:
require_once("Includes/db.php");
2. Replace the following code block:
3. $con = mysql_connect("localhost", "phpuser", "!phpuser");
4. if (!$con) {
5. die('Could not connect: ' . mysql_error());
6. }
7.
8. mysql_query("SET NAMES 'utf8'");
9. mysql_select_db("wishlist", $con);
10.$wisher = mysql_query("SELECT ID FROM wishers WHERE
name='".mysql_real_escape_string($_GET["user"])."'");
11.if (mysql_num_rows($wisher)<1) {
12. die("The person " .$_GET["user"]. " is not found. Please check the spelling
and try again" );
13.}
$wisherID = mysql_result($wisher, 0);
with the following lines of code:
$wisherID = WishDB::getInstance()->get_wisher_id_by_name($_GET["user"]);
if (!$wisherID) {
die("The person " .$_GET["user"]. " is not found. Please check the spelling
and try again" );
}
This code first calls the getInstance function in WishDB. getInstance returns an instance of
WishDB, and the code calls the get_wisher_id_by_name function within that instance. If the
requested wisher is not found in the database, the code kills the process and displays an error
message.
No code is necessary here for opening a connection to the database. The connection is opened by the
constructor of the WishDB class. If the name and/or password changes, you need to update only the
relevant variables of the WishDB class.
14.Replace the following code:
$result = mysql_query("SELECT * FROM wishes WHERE Wisherid=". $wisherID);
with a call of the function get_wishes_by_wisher_id:
$result = WishDB::getInstance()->get_wishes_by_wisher_id($wisherID);
with code that calls that gets an instance of WishDB and calls the
get_wisher_id_by_name function from that instance:
$wisherID = WishDB::getInstance()->get_wisher_id_by_name($_POST["user"]);
if ($wisherID) {
$userNameIsUnique = false;
}
The WishDB object exists as long as the current page is being processed. It is destroyed
after the processing is completed or interrupted. The code for opening a connection to
the database is not necessary because this is done by the WishDB function. The code
for closing the connection is not necessary because the connection is closed as soon as
the WishDB object is destroyed.
session_start();
$_SESSION["user"] = $_POST["user"];
The code block starts a session, which means opening the $_SESSION array for entering or
retrieving data. Then the code adds an element to the $_SESSION array. The added element
contains a value and an identifier (key). The value is the name of the newly created wishers
and the identifier is "user". Then the program redirects the wisher to the editWishList.php
page.
session_start();
if (array_key_exists("user", $_SESSION)) {
echo "Hello " . $_SESSION["user"];
}
The code block opens the $_SESSION array for retrieving data and verifies that $_SESSION contains an
element with the identifier "user". If the check is successful, the code prints a welcome message.
To check that the session is implemented correctly:
1. Run the createNewWisher.php file and create a new wisher, for example Jack.
The editWishList.php opens with Hello Jack.
2. Clear session cookies in your browser or end the session and run editWishList.php from
the IDE.
The editWishList.php file opens with Hello because no user has been transferred
through a session. This is not correct because it enables someone who is not logged in
and not registered to create or edit a wish list. In order to avoid this, the user needs to
be redirected to the index.php page.
else {
header('Location: index.php');
exit;
}
The code redirects the user to the index.php page and cancels PHP code execution.
To check that the functionality is implemented correctly, run the editWishList.php file. The
expected result is that the index.php page opens.
Source of Redirection
A user may access the index.php page on starting the application, or from the editWishList.php page, or
when redirected from the index.php page after entering name and password.
Because only in the last case is the HTML request method POST used, you can always learn where the user
was located when they accessed index.php.
In the index.php file, create a <?php ?> block above the HTML block, with the following code:
<?php
require_once("Includes/db.php");
$logonSuccess = true;
if ($_SERVER["REQUEST_METHOD"] == "POST"){
if (WishDB::getInstance()->verify_wisher_credentials($_POST["user"],
$_POST["userpassword"]) == 1) {
session_start();
$_SESSION["user"] = $_POST["user"];
header('Location: editWishList.php');
} else {
$logonSuccess = false;
}
}
If the request method is POST, which means that the user was redirected from the index.php page, the code
block calls the verify_wisher_credentials function with the name and password entered during logon.
If the verify_wisher_credentials function returns 1, which means that a wisher with the specified
combination of name and password is registered in the database, the $_SESSION array is opened for entering
data. Then a new element is added to the $_SESSION array. The element contains a value and an identifier
(key). The value is the name of the wisher and the identifier is "user". Then the user is redirected to the
editWishList.php page in order to edit the wish list.
If the verify_wisher_credentials function does not return 1, the value of the $logonSuccess variable is
changed to false. The value of the variable is used in displaying an error message.
Function verify_wisher_credentials
In order to implement verification of the wisher's credentials, you need to add a new function to the WishDB
class in the db.php file. The function requires a name and a password as the input parameters and returns 0
or 1.
Enter the following code block:
public function verify_wisher_credentials ($name, $password){
return mysql_num_rows(mysql_query("SELECT * FROM wishers
WHERE name = '" . $name . "' AND password = '" . $password . "'"));
}
The code block executes the query "SELECT * FROM wishers WHERE Name = '" . $name . "'
AND Password = '" . $password . "'" and returns the number of records that meet the
specified query. 1 is returned if such record is found and 0 is returned if there is no such
record in the database.
<?php
if (!$logonSuccess)
echo "Invalid name and/or password";
?>
The code block checks the value of the $logonSuccess variable and if it is false, displays an
error message.
4. Enter Tom in the Username edit box and tomcat in the Password edit box.
5. Press Edit My Wish list. The editWishList.php page is displayed:
session_start();
if (!array_key_exists("user", $_SESSION)) {
header('Location: index.php');
exit;
}
The code:
function format_date_for_sql($date){
if ($date == "")
return "NULL";
else {
$dateParts = date_parse($date);
return $dateParts["year"]*10000 + $dateParts["month"]*100 + $dateParts["day"];
}
}
If the input string is empty, the code returns NULL. Otherwise, the internal date_parse function
is called with the $date as the input parameter. The date_parse function returns an array that
consists of three elements named $dateParts["year"], $dateParts["month"], and
$dateParts["day"]. The final output string is constructed of the elements of the $dateParts
array.
require_once("Includes/db.php");
$wisherId = WishDB::getInstance()->get_wisher_id_by_name($_SESSION["user"]);
$wishDescriptionIsEmpty = false;
if ($_SERVER["REQUEST_METHOD"] == "POST"){
if (array_key_exists("back", $_POST)) {
header('Location: editWishList.php' );
exit;
} else
if ($_POST["wish"] == "") {
$wishDescriptionIsEmpty = true;
}
else {
WishDB::getInstance()->insert_wish($wisherId, $_POST["wish"],
$_POST["dueDate"]);
header('Location: editWishList.php' );
exit;
}
}
<?php
if ($wishDescriptionIsEmpty) echo "Please enter description<br/>";
?>
The error message is displayed if the $wishDescriptionIsEmpty flag is true. The flag is
processed during the input form validation.
3. Press the Back to Main Page button. The index.php page opens.
4. Logon as Tom and press the Edit My Wish List button again. The editWishList.php page
opens.
5. Press the Add Wish button. The editWish.php page opens. Fill in the form.
Press the Back to the List button. The editWishList.php page opens but the entered
wish is not added.
6. Press the Add Wish button again. The editWish.php page opens. Fill in the due date and
leave the description empty. Press the Save Changes button. The editWish.php page
displays the input form with an error message and filled in due date.
7. Press the Add Wish button again. The editWish.php page opens. Fill in the form and
press the Save Changes button. The editWishList.php page shows an updated list of
wishes.
• On the editWishList.php page, the user presses the Edit button to the right of a wish.
The editWish.php page with the data of the selected wish opens.
• The user changes the description and/or the due date of the wish and presses the Save
Changes button.
• If the description is not filled in, an error message is displayed and the user returns to
the editWish.php page.
• If the description is filled in, the application returns to the editWishList.php page,
where the wish is updated.
The implementation consists of the following steps:
• Adding an Edit button on the editWishList page
• On the editWish.php page, updating the array $wish for storing wish data
• Updating the input form on the editWish.php page..
• Validation of the submitted data and updating the wish in the database..
?>
3. To implement the Edit button, add a table inside the "while" loop. To put an HTML table
inside the loop, first delete the closing curly braket from the loop, then type or paste
the following code beneath the PHP block. The while loop is now closed by the bracket
in the PHP block you added after the table, after the echo "</tr>\n"; operation.
4. <td>
5. <form name="editWish" action="editWish.php" method="GET">
6. <input type="hidden" name="wishID" value="<?php echo $wishID; ?>"/>
7. <input type="submit" name="editWish" value="Edit"/>
8. </form>
9. </td>
10.<?php
11. echo "</tr>\n";
12.}
?>
The entire table, including the form with the Edit button inside the while loop, now looks like this:
<table border="black">
<tr><th>Item</th><th>Due Date</th></tr>
<?php
require_once("Includes/db.php");
$wisherID = WishDB::getInstance()-
>get_wisher_id_by_name(mysql_real_escape_string($_SESSION["user"]));
$result = WishDB::getInstance()->get_wishes_by_wisher_id($wisherID);
while($row = mysql_fetch_array($result)) {
strip_tags($row["description"],'<br><p><h1>');
echo "<tr><td>" . $row["description"]."</td>";
strip_tags($row["due_date"],'<br><p><h1>');
echo "<td>".$row["due_date"]."</td>";
echo "</tr>\n";
$wishID = $row["id"];
?>
<td>
<form name="editWish" action="editWish.php" method="GET">
<input type="hidden" name="wishID" value="<?php echo $wishID; ?
>"/>
<input type="submit" name="editWish" value="Edit"/>
</form>
</td>
<?php
echo "</tr>\n";
}
?>
</table>
The form contains a submit field, which implements the Edit button, and a hidden field wishID for
transferring the ID of the wish displayed to left of the Edit button. The ID of the wish is stored in the
$wishID variable.
13.Remove the first echo "</tr>\n"; operation, the one above $wishID = $row["id"].
Otherwise you close the row before the last </td> and your table will not display
correctly.
6. In the main PHP block of editWish.php, add a condition to the else statement that
inserts the wish to the database, changing it to an else if statement:
else if ($_POST["wishID"]=="") {
WishDB::getInstance()->insert_wish($wisherId, $_POST["wish"],
$_POST["dueDate"]);
header('Location: editWishList.php' );
exit;
}
7. Type or paste another else if statement below the one you just edited:
8. else if ($_POST["wishID"]!="") {
WishDB::getInstance()->update_wish($_POST["wishID"], $_POST["wish"],
$_POST["dueDate"]);
header('Location: editWishList.php' );
exit;
}
The code checks that the wishID element in the $_POST array is not an empty string, which means that the
user was redirected from the editWishList.php page by pressing the Edit button and that the user has filled
in the description of the wish. If the check is successful, the code calls the function update_wish with the
input parameters wishID, description, and dueDate. These parameters are received from the HTML
input form through the POST method. After update_wish is called, the application is redirected to the
editWishList.php page and the PHP processing is canceled.
Testing the Edit Wish Functionality
1. Run the application. On the index.php page, fill in the fields: in the Username field,
enter "Tom", in the Password field, enter "tomcat".
2. Press the Edit My Wish List button. The editWishList.php page opens.
4. Edit the fields and press Back to the List. The editWishList.php page opens but the
changes are not saved.
5. Press Edit next to Icecream. Clear the Describe your wish field and press Save Changes.
An error message is displayed.
6. Enter Chocolate icecream in the Describe your wish field and press Save Changes. The
editWishList.php page opens with the updated list.
Deleting a Wish
Now that you can create, read, and update wishes, add functionality for deleting a wish.
To enable the user to delete wishes:
1. Add a delete_wish function to db.php.
2. function delete_wish ($wishID){
return mysql_query("DELETE FROM wishes WHERE id = " . $wishID);
}
3. Create a new PHP file named deleteWish.php and enter the following code into the <?
php ?> block:
require_once("Includes/db.php");
WishDB::getInstance()->delete_wish ($_POST["wishID"]);
header('Location: editWishList.php' );
The code enables the use of the db.php file. It then calls the function delete_wish from
an instance of WishDB, with the wishID as the input parameter. Finally, the application
is redirected to the editWishList.php page.
4. To implement the Delete button, enter the following code block inside the while loop in
editWishList.php, directly below the code block for the editWish button:
5. <td>
6. <form name="deleteWish" action="deleteWish.php" method="POST">
7. <input type="hidden" name="wishID" value="<?php echo $wishID; ?>"/>
8. <input type="submit" name="deleteWish" value="Delete"/>
9. </form>
</td>
The HTML input form contains a hidden field for the wishID and a submit button labelled
Delete.
Lesson 8: Making the Application Look Better Using the CSS Technology
In this lesson you learn how to do the following:
• Hide input forms when they are not used by implementing JavaScript functions
• Improve the appearance of tables with empty cells.
• Define the styles and positioning of page elements by applying Cascading Style Sheet
• Implement the application design using divs.
The current document is a part of the Creating a CRUD Application in the NetBeans IDE for PHP tutorial.
Hiding Forms
Presently, the main index.php page of your application always displays the entire logon and showWishList
forms. To improve the appearance of your application, you can hide the forms and replace them with
buttons. When the user presses a button the corresponding hidden form expands.
To implement this behavior:
1. Add a <script></script> block to the index.php file right above the closing </body>
tag.
2. Develop two JavaScript functions inside the tags.
3. Make some minor changes to the index.php file
JavaScript Functions
JavaScript functions do not require any input parameters and do not return any result. The following code
checks the visibility status of the corresponding form and changes it to the opposite status. It also changes
the text on the button. To accomplish these changes, enter the following code inside the <script></scrip>
tags:
function showHideLogonForm() {
if (document.all.logon.style.visibility == "visible"){
document.all.logon.style.visibility = "hidden";
document.all.myWishList.value = "My Wishlist >>";
}
else {
document.all.logon.style.visibility = "visible";
document.all.myWishList.value = "<< My Wishlist";
}
}
function showHideShowWishListForm() {
if (document.all.wishList.style.visibility == "visible") {
document.all.wishList.style.visibility = "hidden";
document.all.showWishList.value = "Show Wish List of >>";
}
else {
document.all.wishList.style.visibility = "visible";
document.all.showWishList.value = "<< Show Wish List of";
}
}
Updating index.php
1. Add a style attribute to the logon form:
<form name="logon" action="index.php" method="POST" style="visibility:<?php if
($logonSuccess) echo "hidden";
else echo
"visible";?>">
The style attribute defines whether the form is hidden or visible. The <?php ?> block is
used to keep the form visible until the user logs on successfully.
2. Enter the following code above the logon input form code:
<input type="submit" name="myWishList" value="My Wishlist >>"
onclick="javascript:showHideLogonForm()"/>
The code implements a button with the text "My Wishlist >>". The button stands in
place of the logon form. Pressing the button calls the showHideLogonForm function.
<div class="table">
<table border="black">
<tr><th>Item</th><th>Due Date</th></tr>
<?php
$result = WishDB::getInstance()->get_wishes_by_wisher_id($wisherID);
while($row = mysql_fetch_array($result)) {
echo "<tr><td> " . $row["description"]."</td>";
echo "<td> ".$row["due_date"]."</td></tr>\n";
}
?>
</table>
</div>
Defining Styles Using the Cascading Style Sheet
Presently the controls in your application "stick" to each other and are usually placed in the upper left-hand
corner of the screen. To improve the appearance of you application's pages, specify the size, position, color,
font, and other parameters of controls by defining styles and assigning these styles to particular controls.
Styles are defined in a separate Cascading Style Sheet (CSS) file.
All the recommendations and suggestions concerning the application design are optional. The style
definitions below are intended just to give you an example of improving the application appearance. The
settings are appropriate for screen resolution 1024x768 pixel or higher.
Creating a CSS File
1. Click the right mouse button on the Source Files node and from the context menu
choose New > Cascading Style Sheet.
2. On the Cascading Style Sheet panel, in the File Name edit box enter wishlist. Click
Finish.
• Two styles: "body" and "input" - that are automatically applied inside any
<body></body> or <input/> tag.
• CSS classes that are applied when explicitly specified. The names of classes have dots
in preposition, for example,.createWishList. Some classes are used several times, for
example, the ".error" class is applied to all error messages in the application. Other
classes are used only once, for example, ".showWishList", ".logon".
Implementing the Design Using HTML Divs
All the recommendations and suggestions concerning the application design are optional. Like the style
definitions above they are intended just to give you an example of how to improve the application's
appearance.
The example below shows how you can improve the appearance of the index.php page.
index.php
1. To enable using the CSS classes that you defined, enter the following code inside the
<head></head> block:
<link href="wishlist.css" type="text/css" rel="stylesheet" media="all" />
The styles "body" and "input" are automatically applied inside the corresponding tags
so you do need to indicate them explicitly.
2. To apply any other style (class) to an area, enclose the code that implements the area
in the <div class=""></div> tags:
<div class="showWishList">
<input type="submit" name="showWishList" value="Show Wish List of >>"
onclick="javascript:showHideShowWishListForm()"/>