Lesson 3: Creating a New Application User
This tutorial needs a review. You can edit it in GitHub following these contribution guidelines. |
In this lesson you expand the application with the Create a New Wisher functionality.
The implementation will affect the index.php file and two new files will be created named createNewWisher.php
and editWishList.php
.
The Create a New Wisher use case consists of three steps:
-
The user opens the front page index.php and clicks the link to register.
-
The user switches to the createNewWisher.php page for creating a new wisher.
-
After creating a new wisher, the user switches to editWishList.php, where he creates a wish list for the user.
The current document is a part of the Creating a Database Application in the NetBeans IDE for PHP tutorial.
Adding a Link to Start Creating a New Wisher
Open index.php
. Add a blank line below the closing </form> tag. In that blank line, enter the following code block:
<br>Still don't have a wish list?! <a href="createNewWisher.php">Create now</a>
Where:
-
`Still don’t have a wish list?! ` is the text that will be displayed on the page next to the link.
-
<a href="createNewWisher.php"></a>
is the code that implements a link that opens the createNewWisher.php page. -
Create now
is the text that will be displayed as a link.
Creating New PHP Web Pages
Create two new PHP web pages in your project’s Source Files, as described in Lesson 2.
-
createNewWisher.php
-
editWishList.php
In editWishList.php
, add the text "Hello!" to the HTML body and otherwise leave it with its default content. You will modify this file in later lessons, but you need it to exist now because createNewWisher.php
references it. For the remainder of this lesson, you modify createNewWisher.php
.
Adding an HTML Form for Entering the Data of a New Wisher
Type or paste the following HTML block into createNewWisher.php
, beneath the PHP block:
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body>Welcome!<br><form action="createNewWisher.php" method="POST">Your name: <input type="text" name="user"/><br/>Password: <input type="password" name="password"/><br/>Please confirm your password: <input type="password" name="password2"/><br/><input type="submit" value="Register"/></form></body>
</html>
The password type is a special type of a text field where characters are replaced with asterisks. The code presents an HTML form for a user to enter the name and password of the new wisher in the text fields. When the user clicks the "Register" button, the entered data is transferred for validation to the same page, createNewWisher.php .
|
You can ignore warnings from the HTML validator. |
Validating Data and Adding It to the Database
In this section you add PHP code to createNewWisher.php
. Add this code to the PHP block at the top of the file. The PHP block must be above all HTML code, empty lines, or whitespace. The position of the PHP code block is important to enable correct functioning of the redirection statement. Within the PHP block, type or paste the code blocks described below in this section, in the order they are written.
Add the following code to validate data:
-
Initialize variables. The first variables pass database credentials and the others are the variables that will be used in the PHP operations.
/** database connection credentials */
$dbHost="localhost";
//on MySql
$dbXeHost="localhost/XE";
$dbUsername="phpuser";
$dbPassword="phpuserpw";
/** other variables */
$userNameIsUnique = true;
$passwordIsValid = true;
$userIsEmpty = false;
$passwordIsEmpty = false;
$password2IsEmpty = false;
-
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.
/** Check that the page was requested from itself via the POST method. */
if ($_SERVER["REQUEST_METHOD"] == "POST") {
}
-
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.
/** Check that the page was requested from itself via the POST method. */
if ($_SERVER["REQUEST_METHOD"] == "POST") {
/** Check whether the user has filled in the wisher's name in the text field "user" */ *
if ($_POST["user"]=="") {
$userIsEmpty = true;
}*
}
-
Add code that establishes a database connection. If the connection cannot be established, the MySQL or Oracle OCI8 error is sent to the output.
For the MySQL database:
/** Check that the page was requested from itself via the POST method. */
if ($_SERVER["REQUEST_METHOD"] == "POST") {
/** Check whether the user has filled in the wisher's name in the text field "user" */
if ($_POST["user"]=="") {
$userIsEmpty = true;
}
/** Create database connection */*$con = mysqli_connect($dbHost, $dbUsername, $dbPassword);
if (!$con) {
exit('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
//set the default client character set
mysqli_set_charset($con, 'utf-8');*
}
For the Oracle database:
/** Check that the page was requested from itself via the POST method. */
if ($_SERVER['REQUEST_METHOD'] == "POST") {
/** Check whether the user has filled in the wisher's name in the text field "user" */
if ($_POST['user'] == "") {
$userIsEmpty = true;
}
/** Create database connection */*$con = oci_connect($dbUsername, $dbPassword, $dbXeHost, "AL32UTF8");
if (!$con) {
$m = oci_error();
exit('Connect Error' . $m['message']);
}*
}
-
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."
For the MySQL database:
/** Check that the page was requested from itself via the POST method. */
if ($_SERVER["REQUEST_METHOD"] == "POST") {
/** Check whether the user has filled in the wisher's name in the text field "user" */
if ($_POST["user"]=="") {
$userIsEmpty = true;
}/** Create database connection */$con = mysqli_connect($dbHost, $dbUsername, $dbPassword);if (!$con) {exit('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());}*/**set the default client character set */
mysqli_set_charset($con, 'utf-8');*
*/** Check whether a user whose name matches the "user" field already exists */**mysqli_select_db($con, "wishlist");
$user = mysqli_real_escape_string($con, $_POST["user"]);
$wisher = mysqli_query($con, "SELECT id FROM wishers WHERE name='".$user."'");
$wisherIDnum=mysqli_num_rows($wisher);
if ($wisherIDnum) {
$userNameIsUnique = false;
}*
}
For the Oracle database:
/** Check that the page was requested from itself via the POST method. */
if ($_SERVER['REQUEST_METHOD'] == "POST") {
/** Check whether the user has filled in the wisher's name in the text field "user" */
if ($_POST['user'] == "") {
$userIsEmpty = true;
}
/** Create database connection */$con = oci_connect($dbUsername, $dbPassword, $dbXeHost, "AL32UTF8");
if (!$con) {
$m = oci_error();
exit('Connection Error ' . $m['message']);
}
*/** Check whether a user whose name matches the "user" field already exists */*
*$query = "SELECT id FROM wishers WHERE name = :user_bv";
$stid = oci_parse($con, $query);
$user = $_POST['user'];
$wisherID = null;
oci_bind_by_name($stid, ':user_bv', $user);
oci_execute($stid);
// Each user name should be unique. Check if the submitted user already exists.
$row = oci_fetch_array($stid, OCI_ASSOC);
if ($row){
$userNameIsUnique = false;
}*
}
-
After the code that checks if the user is unique, add a series of `if ` clauses that check whether the user entered and confirmed a password correctly. The code checks that the Password ("password") and Confirm Password ('password2) fields are not empty in the form and that they are identical. Otherwise the values of the corresponding boolean variables are changed accordingly.
if ($_POST["password"]=="") {$passwordIsEmpty = true;
}if ($_POST["password2"]=="") {$password2IsEmpty = true;
}if ($_POST["password"]!=$_POST["password2"]) {$passwordIsValid = false;
}
-
Complete the
if ($_SERVER['REQUEST_METHOD'] == "POST")
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 pageeditWishList.php
.
For the MySQL database:
/** Check that the page was requested from itself via the POST method. */
if ($_SERVER['REQUEST_METHOD'] == "POST") {
/** Check whether the user has filled in the wisher's name in the text field "user" */
if ($_POST['user'] == "") {
$userIsEmpty = true;
}
/** Create database connection */
$con = mysqli_connect($dbHost, $dbUsername, $dbPassword);
if (!$con) {
exit('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
//set the default client character set
mysqli_set_charset($con, 'utf-8');
/** Check whether a user whose name matches the "user" field already exists */
mysqli_select_db($con, "wishlist");
$user = mysqli_real_escape_string($con, $_POST['user']);
$wisher = mysqli_query($con, "SELECT id FROM wishers WHERE name='".$user."'");
$wisherIDnum=mysqli_num_rows($wisher);
if ($wisherIDnum) {
$userNameIsUnique = false;
}
/** Check whether a password was entered and confirmed correctly */
if ($_POST['password'] == "") {
$passwordIsEmpty = true;
}
if ($_POST['password2'] == "") {
$password2IsEmpty = true;
}
if ($_POST['password'] != $_POST['password2']) {
$passwordIsValid = false;
}
/** Check whether the boolean values show that the input data was validated successfully.
* If the data was validated successfully, add it as a new entry in the "wishers" database.
* After adding the new entry, close the connection and redirect the application to editWishList.php.
*/
*if (!$userIsEmpty && $userNameIsUnique && !$passwordIsEmpty && !$password2IsEmpty && $passwordIsValid) {
$password = mysqli_real_escape_string($con, $_POST['password']);
mysqli_select_db($con, "wishlist");
mysqli_query($con, "INSERT wishers (name, password) VALUES ('" . $user . "', '" . $password . "')");
mysqli_free_result($wisher);
mysqli_close($con);
header('Location: editWishList.php');
exit;
}*
}
For the Oracle database:
/** Check that the page was requested from itself via the POST method. */
if ($_SERVER['REQUEST_METHOD'] == "POST") {
/** Check whether the user has filled in the wisher's name in the text field "user" */
if ($_POST['user'] == "")
$userIsEmpty = true;
/** Create database connection */
$con = oci_connect($dbUsername, $dbPassword, $dbXeHost, "AL32UTF8");
if (!$con) {
$m = oci_error();
echo $m['message'], "\n";
exit;
}
/** Check whether a user whose name matches the "user" field already exists */
$query = "select ID from wishers where name = :user_bv";
$stid = oci_parse($con, $query);
$user = $_POST['user'];
$wisherID = null;
oci_bind_by_name($stid, ':user_bv', $user);
oci_execute($stid);
/**Each user name should be unique. Check if the submitted user already exists. */
$row = oci_fetch_array($stid, OCI_ASSOC);
if ($row) {
$wisherID = $row['ID'];
}
if ($wisherID != null) {
$userNameIsUnique = false;
}
//Check for the existence and validity of the password
if ($_POST['password'] == "") {
$passwordIsEmpty = true;
}
if ($_POST['password2'] == "") {
$password2IsEmpty = true;
}
if ($_POST['password'] != $_POST['password2']) {
$passwordIsValid = false;
}
/** Check whether the boolean values show that the input data was validated successfully.
* If the data was validated successfully, add it as a new entry in the "wishers" database.
* After adding the new entry, close the connection and redirect the application to editWishList.php.
*/
*if (!$userIsEmpty && $userNameIsUnique && !$passwordIsEmpty && !$password2IsEmpty && $passwordIsValid) {
$query = "INSERT INTO wishers (name, password) VALUES (:user_bv, :pwd_bv)";
$stid = oci_parse($con, $query);
$pwd = $_POST['password'];
oci_bind_by_name($stid, ':user_bv', $user);
oci_bind_by_name($stid, ':pwd_bv', $pwd);
oci_execute($stid);
oci_free_statement($stid);
oci_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.
-
Enter the following PHP code block inside the HTML input form, below the wisher’s name input:
Welcome!<br><form action="createNewWisher.php" method="POST">Your name: <input type="text" name="user"/><br/>
*<?php
if ($userIsEmpty) {
echo ("Enter your name, please!");
echo ("<br/>");
}
if (!$userNameIsUnique) {
echo ("The person already exists. Please check the spelling and try again");
echo ("<br/>");
}
?> *
-
Enter the following PHP code block inside the HTML input form below the code for the password input:
Password: <input type="password" name="password"/><br/>
*<?php
if ($passwordIsEmpty) {
echo ("Enter the password, please!");
echo ("<br/>");
}
?>*
-
Enter the following PHP code blocks inside the HTML input form below the code for password confirmation:
Please confirm your password: <input type="password" name="password2"/><br/>
*<?php
if ($password2IsEmpty) {
echo ("Confirm your password, please");
echo ("<br/>");
}
if (!$password2IsEmpty && !$passwordIsValid) {
echo ("The passwords do not match!");
echo ("<br/>");
}
?>*
Testing the Create New Wisher Functionality
-
Run the application. The index page opens.
-
On the index page, click the link next to the text Still don’t have a wish list? The following form opens:
-
Leave the fields empty and click Register. An error message displays.
-
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.
-
Fill in the Password and Please confirm your password fields with different values and click Register. An error message displays.
-
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:
-
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