使用 PHP 创建数据库驱动的应用程序
第 3 课:创建新的应用程序用户
在本课中,将使用“创建新的许愿者”功能扩展应用程序。
该实现影响 index.php 文件和将要创建的两个新文件(名为 createNewWisher.php 和 editWishList.php)。
“创建新的许愿者”用例包含两个步骤:
1. 用户打开主页 index.php,然后单击链接以进行注册。
2. 用户切换到 createNewWisher.php 页以创建新的许愿者。
3. 在创建新的许愿者后,用户将切换到 editWishList.php,他可以在其中为该用户创建心愿列表。
当前文档是“在适用于 PHP 的 NetBeans IDE 中创建 CRUD 应用程序”教程的一部分。
来自上一课的应用程序源代码
MySQL 用户:单击此处以下载源代码,该代码反映了在完成上一课后的项目状态。
Oracle 数据库用户:单击此处以下载源代码,该代码反映了在完成上一课后的项目状态。
添加链接以开始创建新的许愿者
打开
index.php。在结束 </form> 标记下面添加一个空行。在该空行中,输入以下代码块:
<br>Still don't have a wish list?! <a href="createNewWisher.php">Create now</a>
其中:
- Still don't have a wish list?! 是在页面上的链接旁边显示的文本。
- <a href="createNewWisher.php"></a> 是实现打开 createNewWisher.php 页的链接的代码。
- Create now 是作为链接显示的文本。
创建新的 PHP 文件
在项目的“源文件”节点中创建两个新的 PHP 文件,如第 2 课中所述。
- createNewWisher.php
- editWishList.php
在 editWishList.php 中,将文本 "Hello!" 添加到 HTML 主体中,否则,保留其缺省内容。将在后面的课程中修改该文件,但您需要现在创建该文件,因为 createNewWisher.php 引用该文件。在本课的其余部分中,将修改 createNewWisher.php。
添加 HTML 表单以输入新的许愿者数据
在 createNewWisher.php 中,在 PHP 块下面键入或粘贴以下 HTML 块:
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</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>
注意:password 类型是一种特殊的文本字段类型,其中将字符替换为星号。该代码显示一个 HTML 表单,以使用户在文本字段中输入新许愿者的名字和口令。在用户单击 "Register" 按钮时,输入的数据将传输到相同页 (createNewWisher.php) 以进行验证。
注意:您可以忽略来自 HTML 验证器的警告。
验证数据并将其添加到数据库中
在本节中,将在 createNewWisher.php 中添加 PHP 代码。将该代码添加到文件顶部的 PHP 块中。PHP 块必须在所有 HTML 代码上面,是空行或是空白内容。要使重定向语句正常工作,PHP 代码块位置是非常重要的。在 PHP 块中,按写入顺序键入或粘贴本节下面介绍的代码块。
添加以下代码以验证数据:
- 初始化变量。前几个变量用于传送数据库凭证,其他变量在 PHP 操作中使用。
/** database connection credentials */
$dbHost="localhost";
$dbUsername="phpuser";
$dbPasswd="phpuserpw";
/** other variables */
$userNameIsUnique = true;
$passwordIsValid = true;
$userIsEmpty = false;
$passwordIsEmpty = false;
$password2IsEmpty = false;
- 在这些变量下面,添加一个 if 子句。if 子句的参数检查页面是不是通过 POST 方法从本身请求的。如果不是,并不执行进一步的验证,而是显示包含空字段的页面,如上所述。
if ($_SERVER["REQUEST_METHOD"] == "POST") {
}
- 在 if 子句的大括号中,添加另一个 if 子句,用于检查用户是否填写了许愿者的名字。如果文本字段 "user" 为空,则将 $userIsEmpty 值更改为 true。
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if ($_POST["user"]=="")
$userIsEmpty = true;
}
添加代码以建立数据库连接。如果无法建立连接,则将 MySQL 或 Oracle OCI8 错误发送到输出。
对于 MySQL 数据库:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if ($_POST["user"]=="") {
$userIsEmpty = true;
}
$con = mysqli_connect("localhost", "phpuser", "phpuserpw");
if (!$con) {
exit('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
//set the default client character set
mysqli_set_charset($con, 'utf-8');
}
对于 Oracle 数据库:
if ($_SERVER['REQUEST_METHOD'] == "POST") {
if ($_POST['user'] == "")
$userIsEmpty = true;
$con = oci_connect("phpuser", "phpuserpw", "localhost/XE");
if (!$con) {
$m = oci_error();
exit('Connect Error' . $m['message']);
}
}
- 添加代码以检查名字与 "user" 字段匹配的用户是否已存在。该代码的工作方式是,尝试查找名字与 "user" 字段中的名字匹配的许愿者 ID 号。如果该 ID 号存在,则将 $userNameIsUnique 值更改为 "false"。
对于 MySQL 数据库:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
Displaying error messages
if ($_POST["user"]=="") {
$userIsEmpty = true;
}
$con = mysqli_connect("localhost", "phpuser", "phpuserpw");
if (!$con) {
exit('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
//set the default client character set
mysqli_set_charset($con, 'utf-8');
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;
}
}
对于 Oracle 数据库:
if ($_SERVER['REQUEST_METHOD'] == "POST") {
if ($_POST['user'] == "")
$userIsEmpty = true;
$con = oci_connect("phpuser", "phpuserpw", "localhost");
if (!$con) {
$m = oci_error();
exit('Connection Error ' . $m['message']);
}
$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;
}
}
- 在检查用户是否唯一的代码后面,添加一系列 if 子句,用于检查用户是否正确输入了口令和确认口令。该代码检查表单中的 Password ("password") 和 Confirm Password ('password2) 字段是否为空以及它们是否相同。如果为空或不相同,则会更改相应的布尔型变量。
if ($_POST["password"]=="")
$passwordIsEmpty = true;
if ($_POST["password2"]=="")
$password2IsEmpty = true;
if ($_POST["password"]!=$_POST["password2"]) {
$passwordIsValid = false;}
-
通过添加在 "wishers" 数据库中插入新条目的代码,完成 if ($_SERVER['REQUEST_METHOD'] == "POST") 子句。该代码检查是否唯一地指定许愿者名字,以及是否正确输入了口令和确认口令。如果符合这些条件,该代码将从 HTML 表单中提取 "user" 和 "password" 值,然后将其分别插入到 wishers 数据库的新行中的 Name 和 Password 列。在创建该行后,该代码将关闭数据库连接并将应用程序重定向到 editWishList.php 页。
对于 MySQL 数据库:
/** 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("localhost", "phpuser", "phpuserpw");
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;
}
}
对于 Oracle 数据库:
if ($_SERVER['REQUEST_METHOD'] == "POST") {
if ($_POST['user'] == "")
$userIsEmpty = true;
$con = oci_connect("phpuser", "phpuserpw", "localhost/XE", "AL32UTF8");
if (!$con) {
$m = oci_error();
echo $m['message'], "\n";
exit;
}
$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;
}
}
在输入表单中显示错误消息
现在,将实现在输入无效数据时显示错误消息的功能。该实现基于验证和布尔型变量值更改,如验证数据并将其添加到数据库中中所述。
- 在 HTML 输入表单中,在许愿者名字输入代码下面输入以下 PHP 代码块:
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/>");
}
?>
- 在 HTML 输入表单中,在口令输入代码下面输入以下 PHP 代码块:
Password: <input type="password" name="password"/><br/>
<?php
if ($passwordIsEmpty) {
echo ("Enter the password, please!");
echo ("<br/>");
}
?>
- 在 HTML 输入表单中,在口令确认代码下面输入以下 PHP 代码块:
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/>");
}
?>
测试“创建新的许愿者”功能
- 运行应用程序。将打开索引页。

- 在索引页中,单击 Still don't have a wish list? 文本旁边的链接。将打开以下表单:

- 将这些字段保留空白,然后单击 "Register"。将显示一条错误消息。

- 在 "Your name" 字段中输入注册的许愿者名字(如 Tom),正确填写其他字段,然后单击 "Register"。将显示一条错误消息。
- 使用不同的值填写 "Password" 和 "Please confirm your password" 字段,然后单击 "Register"。将显示一条错误消息。
- 在 "Your name" 字段中输入 Bob,在两个口令字段中指定相同的口令,然后单击 "Register"。打开的页为空页,但正确传送了重定向,因为 URL 以 editWishList.php 结尾:

- 要检查数据是否存储在数据库中,请导航到“服务”窗口中的 wislist1 节点下面的 wishers,然后从上下文菜单中选择“查看数据”。
