前面几篇文章介绍了php应用程序环境搭建、mysql数据库的基本操作,现在通过一个实例来展现完整的php web应用程序。
首先,创建一个mysql数据库books,新建用户、密码及权限,新建数据库表book并插入几条数据,具体操作请参考上一篇文章。
然后,在NetBeans IDE中新建一个php项目,新建html文件search.html,用于输入查询条件,代码如下:
<html>
<head>
<title>Book Search</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h1>Book Search</h1>
<form action="results.php" method="post">
Choose Search Type:<br/>
<select name="searchtype">
<option value="author">Author</option>
<option value="title">Title</option>
<option value="isbn">ISBN</option>
</select>
<br/>
Enter search Term:<br/>
<input name="searchterm" type="text" size="40"/>
<br/>
<input type="submit" name="submit" value="Search"/>
</form>
</body>
</html>
新建php文件results.php,具体代码如下:
<html>
<head>
<title>Book Results</title>
</head>
<body>
<h1>Book Results</h1>
<?php
//查询条件
$searchtype = $_POST['searchtype'];
$searchterm = trim($_POST['searchterm']);
if (!$searchtype || !$searchterm) {
echo 'You have not ertered search details. Please go back and try again.';
exit();
}
//获取PHP环境变量magic_quotes_gpc的值,返回值为0表示关闭,1表示打开。
//打开时,所有的 ' (单引号), " (双引号), \ (反斜线) 和 空字符会自动转为含有反斜线的转义字符
if (!get_magic_quotes_gpc()) {
$searchtype = addslashes($searchtype); //在指定的预定义字符( ' (单引号), " (双引号), \ (反斜线), NULL)前添加反斜杠
$searchterm = addslashes($searchterm);
}
$db = new mysqli('localhost', 'book', 'book123', 'books');//参数依次为主机名、用户名、密码、数据库名
//判断数据库连接是否成功
if (mysqli_connect_errno()) {
echo 'Error: Could not connect to database. Please try again later.';
exit();
}
$query = "select * from books where " . $searchtype . " like '%" . $searchterm . "%'";
$result = $db->query($query);
$num_results = $result->num_rows;
echo "<p>Number of books found: " . $num_results . "</p>";
for ($i = 0; $i < $num_results; $i++) {
$row = $result->fetch_assoc();
echo "<p><strong>" . ($i + 1) . ". Title: ";
echo htmlspecialchars(stripcslashes($row['title'])); //htmlspecialchars()将预定义字符串转换为html实体
//stripcslashes()清理从数据库中取回的数据,与addslashes()相对应,去除字符串中的反斜杠
echo "</strong><br/>Author: ";
echo stripslashes($row['author']);
echo "<br/>ISBN: ";
echo stripslashes($row['isbn']);
echo "<br/>Price: ";
echo stripslashes($row['price']);
echo "</p>";
}
$result->free();
$db->close();
?>
</body>
</html>
运行项目,运行项目之前确保MySQL、Apache服务器均正常启动。