第3讲 JavaScript基础

3.1 JavaScript简介

  1. 基本概念
    • JavaScript是一种网页脚本语言,与Java完全不同(语法类似但无关)。
    • 代码可直接嵌入HTML页面,由浏览器解释执行。
  2. 第一个JavaScript程序
    • 大小写敏感:与Java一致。
    • 注释方式
      • HTML注释:<!--注释内容-->
      • 单行注释://注释内容
      • 多行注释:/*注释内容*/
    • 代码嵌入方式
      • 直接在HTML中用<script>标签嵌入。
      • 外部文件:创建.js文件,通过<script src="code.js" type="text/javascript"></script>引入。
  3. JavaScript语法
    • 变量定义
      • 弱类型变量,用var声明(如var arg)。
      • 类型由赋值决定(字符串、数组等)。
      • 注意:未声明变量可能引发错误,建议先声明后使用。
    • 函数定义
      • 标准格式:
        1
        2
        3
        function 函数名(参数列表) {
        return 值;
        }
      • 匿名函数:
        1
        2
        3
        var arg1 = function(参数列表) {
        return 值;
        }

3.2 JavaScript内置对象

  1. 常用内置对象
    • window:操作浏览器窗口(状态、开闭等)。
    • document:操作HTML文档(从属window)。
    • history:访问浏览历史(从属window)。
    • location:操作地址栏(从属window)。
  2. window对象
    • 提示框
      • alert("内容"):消息框。
      • confirm("内容"):确认框(返回true/false)。
      • prompt("内容",默认值):输入框(返回输入值或null)。
    • 窗口操作
      • open("地址", "窗口名", "状态属性"):打开新窗口。
        • 状态属性:toolbar(工具栏)、location(地址栏)、width/height(尺寸)等。
      • close():关闭窗口。
    • 定时器
      • setTimeout("函数", 毫秒):定时执行。
      • clearTimeout(timer):清除定时器。
  3. history对象
    • back():后退一页。
    • forward():前进一页。
    • go(n)n>0前进n页,n<0后退|n|页。
  4. document对象
    • 输出内容writeln()(用于动态生成HTML,如表格)。
    • 设置属性
      • document.title:网页标题。
      • document.location:当前地址。
    • 访问元素
      • 通过元素名访问(如document.form1.account.value获取表单输入值)。
  5. location对象
    • 跳转页面window.location.href="page.html"
    • 定时跳转:结合setTimeout实现自动跳转。

本章总结

  • 语法重点:变量声明、函数定义、注释规则。
  • 内置对象:掌握windowdocumenthistorylocation的核心功能。
  • 实践应用:通过示例代码理解提示框、窗口操作、元素访问等场景。

PHP实验代码合集

实验一:PHP数组基本操作

实验目的

  1. 掌握PHP的数组声明
  2. 掌握PHP的数组定义
  3. 掌握PHP数组的遍历和排序
  4. 熟练运用数组完成相关的任务

实验内容

自己构造一个名字为students的二维数组,每个学号代表一名学生,该学生的信息由"姓名"、“性别”、"成绩"组成,数组中的元素至少具备5条。然后按照学生的成绩高低对该二维数组进行排序,并在网页中显示排序前后的students数组。

实验代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<?php
// 构造students二维数组
$students["000001"] = array("学号"=>"000001","姓名"=>"张三","性别"=>"女","成绩"=>60);
$students["000002"] = array("学号"=>"000002","姓名"=>"张四","性别"=>"女","成绩"=>90);
$students["000003"] = array("学号"=>"000003","姓名"=>"张五","性别"=>"男","成绩"=>85);
$students["000004"] = array("学号"=>"000004","姓名"=>"张六","性别"=>"女","成绩"=>78);
$students["000005"] = array("学号"=>"000005","姓名"=>"张七","性别"=>"男","成绩"=>91);
echo "<table border='1' cellpadding='5' cellspacing='0'>";
echo "<tr><th>学号</th><th>姓名</th><th>性别</th><th>成绩</th></tr>";
foreach ($students as $student) {
echo "<tr>";
echo "<td>{$student['学号']}</td>";
echo "<td>{$student['姓名']}</td>";
echo "<td>{$student['性别']}</td>";
echo "<td>{$student['成绩']}</td>";
echo "</tr>";
}
echo "</table>";
echo "<br><br>";
// 传参到$stu并输出排序后的数组
$stu = $students;
usort($stu, function($a, $b) {
return $b['成绩'] <=> $a['成绩'];
});
echo "<table border='1' cellpadding='5' cellspacing='0'>";
echo "<tr><th>学号</th><th>姓名</th><th>性别</th><th>成绩</th></tr>";
foreach ($stu as $student) {
echo "<tr>";
echo "<td>{$student['学号']}</td>";
echo "<td>{$student['姓名']}</td>";
echo "<td>{$student['性别']}</td>";
echo "<td>{$student['成绩']}</td>";
echo "</tr>";
}
echo "</table>";
echo "<br><br>";
?>

实验二:PHP语法基础

实验目的

  1. 掌握PHP语法基本元素,掌握数据类型、变量和常量、运算符、表达式的使用
  2. 掌握PHP流程控制
  3. 掌握在Html和PHP命令标记相结合的方法

实验内容

  1. PHP语法:数据类型、变量和常量、运算符、表达式、流程控制
  2. PHP和html标记相结合

实验代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>PHP实验2</title>
</head>
<body>
<?php
$xh = "3236021001"; // 给变量$xh赋一个文本数值
?>
<form method="post" action="">
学号:<input type="text" name="xh" value="<?php echo htmlspecialchars($xh); ?>">
<input type="submit" value="提交">
</form>
</body>
</html>
<?php
// 产生一个随机年份
$year = rand();
// 判断是否为闰年
if (($year % 4 == 0 && $year % 100 != 0) || ($year % 400 == 0)) {
$result = "{$year}年是闰年";
} else {
$result = "{$year}年不是闰年";
}
// 显示结果
echo "<p>{$result}</p>";
?>
<table border="1" cellpadding="5" cellspacing="0">
<tr>
<th>信息名称</th>
<th>信息内容</th>
<th>变量名称</th>
</tr>
<tr>
<td>用户操作系统</td>
<td><?php echo isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '未知'; ?></td>
<td>$_SERVER['HTTP_USER_AGENT']</td>
</tr>
<tr>
<td>服务器操作系统</td>
<td><?php echo PHP_OS; ?></td>
<td>PHP_OS</td>
</tr>
<tr>
<td>服务器软件信息</td>
<td><?php echo isset($_SERVER['SERVER_SOFTWARE']) ? $_SERVER['SERVER_SOFTWARE'] : '未知'; ?></td>
<td>$_SERVER['SERVER_SOFTWARE']</td>
</tr>
</table>

实验三:PHP和Html交互及函数的使用

实验目的

  1. 掌握在Html和PHP命令标记相结合的方法
  2. 掌握用PHP和Html交互的处理方法
  3. 掌握php中函数的定义和使用方法

实验内容

  1. PHP和html交互
  2. PHP函数

实验代码

ex3_1.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<title>表单输入读取示例</title>
<script>
function compareValue(i) {
if (i === "") return;
var num = parseInt(i);
if (isNaN(num)) return;
if (num > 5) {
alert("i 大于5");
} else {
alert("i 小于等于5");
}
}
</script>
</head>
<body>
<h2>PHP 读取表单练习</h2>
<form method="post" action="">
请输入变量$i 的数值:<input type="number" id="i" name="i" value="<?php echo isset($_POST['i']) ? htmlspecialchars($_POST['i']) : ''; ?>">
<input type="submit" value="提交" onclick="compareValue(document.getElementById('i').value);">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST["i"]) && $_POST["i"] !== "") {
$i = intval($_POST["i"]);
echo "<div style='margin-top:20px;'>";
$arr = [];
for ($j = 0; $j < $i; $j++) {
$arr[] = $j;
}
echo implode(",", $arr);
echo "</div>";
}
?>
</body>
</html>

ex3_2.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
<?php
/**
* 比较两个数值的大小
* @param int|float $a 第一个数
* @param int|float $b 第二个数
* @param string $option 选项:'B'返回最大值,'L'返回最小值
* @return int|float 根据选项返回最大值或最小值
*/
function compareValues($a, $b, $option) {
// 将选项转换为大写,避免大小写问题
$option = strtoupper($option);
if ($option == 'B') {
// 返回最大值
return max($a, $b);
} elseif ($option == 'L') {
// 返回最小值
return min($a, $b);
} else {
// 如果选项无效,默认返回最大值
return max($a, $b);
}
}
?>
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<title>比较数值大小</title>
</head>
<body>
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$a = $_POST['a'];
$b = $_POST['b'];
$option = $_POST['option'];
$result = compareValues($a, $b, $option);
}
?>
<form method="post" action="">
<table>
<tr>
<td>请输入变量$a 的数值</td>
<td><input type="number" name="a" value="<?php echo $_POST['a'] ?? ''; ?>"></td>
</tr>
<tr>
<td>请输入变量$b 的数值</td>
<td><input type="number" name="b" value="<?php echo $_POST['b'] ?? ''; ?>"></td>
</tr>
<tr>
<td>指定返回数值是</td>
<td>
<select name="option">
<option value="B" <?php echo ($_POST['option'] ?? '') == 'B' ? 'selected' : ''; ?>>最大值</option>
<option value="L" <?php echo ($_POST['option'] ?? '') == 'L' ? 'selected' : ''; ?>>最小值</option>
</select>
</td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="确定"></td>
</tr>
</table>
</form>
<?php
if (isset($result)) {
echo "结果是:<br>";
echo "两者的" . ($option == 'B' ? '最大值是' : '最小值是') . $result;
}
?>
</body>
</html>

实验四:PHP数据处理

实验目的

掌握PHP正则表达式、文件、日期数据的操作方法

实验内容

  1. 正则表达式的使用
  2. 文件的操作
  3. 日期数据的操作

实验代码

ex4_3.php(表单验证)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
<?php
// 简单表单验证:用户名(6-12字符)、密码(6-20位数字)、出生日期(有效日期)、E-mail(有效地址)
function e($s) { return htmlspecialchars($s, ENT_QUOTES, 'UTF-8'); }
$errors = [];
$values = ['username'=>'', 'birthdate'=>'', 'email'=>''];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// 获取原始输入
$username = isset($_POST['username']) ? trim($_POST['username']) : '';
$password = isset($_POST['password']) ? $_POST['password'] : '';
$birthdate = isset($_POST['birthdate']) ? trim($_POST['birthdate']) : '';
$email = isset($_POST['email']) ? trim($_POST['email']) : '';
$values['username'] = $username;
$values['birthdate'] = $birthdate;
$values['email'] = $email;
// 用户名:6-12个字符(字母数字下划线)
if ($username === '') {
$errors[] = '用户名不能为空。';
} elseif (!preg_match('/^[A-Za-z0-9_]{6,12}$/u', $username)) {
$errors[] = '用户名必须为6到12个字符,只允许字母、数字或下划线。';
}
// 密码:6-20位数字
if ($password === '') {
$errors[] = '密码不能为空。';
} elseif (!preg_match('/^[0-9]{6,20}$/', $password)) {
$errors[] = '密码必须为6到20位数字(仅允许0-9)。';
}
// 出生日期:有效日期,格式YYYY-MM-DD,且不晚于今天,年份限制1900-当前年份
if ($birthdate === '') {
$errors[] = '出生日期不能为空。';
} else {
$d = DateTime::createFromFormat('Y-m-d', $birthdate);
$validDate = $d && $d->format('Y-m-d') === $birthdate;
if (!$validDate) {
$errors[] = '出生日期格式不正确,应为YYYY-MM-DD。';
} else {
$year = (int)$d->format('Y');
$today = new DateTime('today');
if ($d > $today) {
$errors[] = '出生日期不能晚于今天。';
} elseif ($year < 1900) {
$errors[] = '出生年份不能早于1900年。';
}
}
}
// E-mail:使用PHP过滤器验证
if ($email === '') {
$errors[] = 'E-mail不能为空。';
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = 'E-mail地址不合法。';
}
// 如果没有错误,可以继续处理(例如保存、注册等)
$ok = empty($errors);
}
if (!empty($errors)) {
echo "<div class='error'>";
echo "<strong>以下错误:</strong> <ul>";
foreach ($errors as $err) {
echo "<li>".e($err)."</li>";
}
echo "</ul>";
echo "</div>";
} elseif (isset($ok) && $ok) {
echo "<div class='success'>";
echo "<p>验证通过!提交的数据:</p> <ul>";
echo "<li>用户名:".e($values['username'])."</li>";
echo "<li>出生日期:".e($values['birthdate'])."</li>";
echo "<li>E-mail:".e($values['email'])."</li>";
echo "</ul>";
echo "</div>";
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>表单验证示例</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<style>
body { font-family: Arial, Helvetica, sans-serif; max-width:760px; margin:30px auto; padding:0 15px; }
.error { color:#a00; }
.success { color:#080; }
form { margin-top:10px; }
label { display:block; margin:10px 0 4px; }
input[type="text"], input[type="password"], input[type="email"], input[type="date"] { width:100%; padding:8px; box-sizing:border-box; }
.note { font-size:0.9em; color:#666; }
</style>
</head>
<body>
<h2>注册 / 验证表单</h2>
<form method="post" action="">
<label for="username">用户名(6-12字符,字母/数字/下划线):</label>
<input type="text" id="username" name="username" pattern="[A-Za-z0-9_]{6,12}" title="6-12个字符,只允许字母、数字或下划线" value="<?php echo e($values['username']); ?>">

<label for="password">密码(6-20位数字):</label>
<input type="password" id="password" name="password" pattern="[0-9]{6,20}" title="6-20位数字,示例:123456" value="<?php echo e($values['password']); ?>">

<label for="birthdate">出生日期:</label>
<input type="date" id="birthdate" name="birthdate" required value="<?php echo e($values['birthdate']); ?>">

<label for="email">E-mail:</label>
<input type="email" id="email" name="email" required value="<?php echo e($values['email']); ?>">

<p class="note">客户端会做基础格式校验,服务器端会做严格验证。</p>
<button type="submit">提交</button>
</form>
</body>
</html>

ex4_4.php(投票系统)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
<?php
// 简单投票脚本,投票结果保存在与此文件同目录的voteresult.txt中,格式:数值用|分隔
$options = ['选项一', '选项二', '选项三', '选项四'];
$dataFile = __DIR__ . '/voteresult.txt';
// 初始化结果文件(若不存在)
if (!file_exists($dataFile)) {
$zeros = implode('|', array_fill(0, count($options), '0')) . "\n";
file_put_contents($dataFile, $zeros, LOCK_EX);
}
// 接收投票
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['option'])) {
$choice = (int)$_POST['option'];
if ($choice >= 0 && $choice < count($options)) {
// 打开文件并加写锁,防止并发写入冲突
$fp = fopen($dataFile, 'c+');
if ($fp) {
if (flock($fp, LOCK_EX)) {
// 读取当前数据
$contents = stream_get_contents($fp);
$contents = trim($contents);

$parts = $contents === '' ? array_fill(0, count($options), 0) : explode('|', $contents);
// 保证数组长度
$counts = array_map('intval', array_pad($parts, count($options), 0));
// 增加选择项
$counts[$choice]++;
// 写回文件
rewind($fp);
ftruncate($fp, 0);
fwrite($fp, implode('|', $counts) . "\n");
fflush($fp);
flock($fp, LOCK_UN);
}
fclose($fp);
}
}
// 避免表单重复提交,重定向回自身
header('Location: ' . $_SERVER['PHP_SELF']);
exit;
}
// 读取当前票数(共享锁)
$counts = array_fill(0, count($options), 0);
$fp = fopen($dataFile, 'r');
if ($fp) {
if (flock($fp, LOCK_SH)) {
$contents = stream_get_contents($fp);
flock($fp, LOCK_UN);
}
fclose($fp);

$contents = trim($contents);
if ($contents !== '') {
$parts = explode('|', $contents);
$counts = array_map('intval', array_pad($parts, count($options), 0));
}
}
$total = array_sum($counts);
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>投票页</title>
<style>
body{font-family: Arial, sans-serif; max-width:640px;margin:2em auto;padding:1em;border:1px solid #ddd;}
.option{margin:0.5em 0;padding:0.5em;border:1px solid #eee;}
.bar{display:inline-block;height:14px;background:#4caf50;vertical-align:middle;}
.count{margin-left:0.6em;color:#333;}
</style>
</head>
<body>
<h2>请选择一个选项并投票</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>">
<?php foreach ($options as $i => $label): ?>
<div class="option">
<label>
<input type="radio" name="option" value="<?php echo $i; ?>" <?php echo $i === 0 ? 'checked' : ''; ?>>
<?php echo htmlspecialchars($label); ?>
</label>
<span class="count"><?php echo $counts[$i]; ?> 票(<?php echo $total ? round($counts[$i] * 100 / $total, 1) : 0; ?>%)</span>
<div style="margin-top:6px;background:#f1f1f1;height:14px;">
<div class="bar" style="width:<?php echo $total ? round($counts[$i] * 100 / $total, 1) : 0; ?>%"></div>
</div>
</div>
<?php endforeach; ?>
<p><button type="submit">投票</button></p>
</form>
<h3>统计</h3>
<p>总票数:<?php echo $total; ?></p>
</body>
</html>

ex4_5.php(年龄计算)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<?php
// 页面:用户输入生日,计算年龄和出生星期
$result = '';
$birthday = $_POST['birthday'] ?? '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (empty($birthday)) {
$result = '请填写生日。';
} else {
try {
$birth = new DateTime($birthday);
$today = new DateTime('today');
if ($birth > $today) {
$result = '生日不能在将来。';
} else {
$age = $birth->diff($today)->y;
$weekdayMap = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
$weekday = $weekdayMap[(int)$birth->format('w')];
$result = sprintf("出生日期:%s;年龄:%d岁;出生星期:%s",
$birth->format('Y-m-d'), $age, $weekday);
}
} catch (Exception $e) {
$result = '无效的日期格式。';
}
}
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>计算年龄与出生星期 - ex4_5.php</title>
</head>
<body>
<h2>请输入您的生日</h2>
<form method="post" action="">
<label>
生日:<input type="date" name="birthday" value="<?php echo htmlspecialchars($birthday); ?>" required>
</label>
<button type="submit">提交</button>
</form>
<?php if ($result !== ''): ?>
<p><strong>结果:</strong><?php echo htmlspecialchars($result); ?></p>
<?php endif; ?>
</body>
</html>

实验五:PHP和数据库

实验目的

掌握PHP连接和操作MySQL数据库的方法

实验内容

用PHP连接和操作MySql的方法

实验代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
<?php
// --- 1. 数据库连接配置 (调试模式)
$db_host = 'localhost';
$db_user = 'admin';
$db_pass = 'admin123';
$db_name = 'ex5';
// 创建数据库连接
$conn = new mysqli($db_host, $db_user, $db_pass, $db_name);
// 检查连接是否成功
if ($conn->connect_error) {
// --- 调试信息:显示详细的连接错误
die("<h3>数据库连接失败!</h3><p><strong>错误详情:</strong>" . $conn->connect_error . "</p><p><strong>请检查:</strong><ul><li>小皮的MySQL服务是否已启动?</li><li>用户名 'admin' 和密码 'admin123' 是否正确?</li><li>数据库名 'ex5' 是否存在?</li><li>用户 'admin' 是否有访问 'ex5' 数据库的权限?</li></ul>");
}
// 设置字符集,防止中文乱码
$conn->set_charset("utf8mb4");
// --- 2. 获取查询参数和分页参数
// 使用isset()防止未定义索引的报错,使用trim()去除前后空格
$s_id = isset($_GET['s_id']) ? trim($_GET['s_id']) : '';
$s_student = isset($_GET['s_student']) ? trim($_GET['s_student']) : '';
$department = isset($_GET['department']) ? trim($_GET['department']) : '';
// 分页参数
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$pageSize = 15; // 每页显示15条记录
$offset = ($page - 1) * $pageSize;
// --- 3. 构建SQL查询语句
// 初始化WHERE条件
$where = [];
$params = [];
$types = '';
// 根据用户输入动态构建WHERE子句
if (!empty($s_id)) {
$where[] = "S_id LIKE ?";
$params[] = "%$s_id%";
$types .= 's';
}
if (!empty($s_student)) {
$where[] = "S_student LIKE ?";
$params[] = "%$s_student%";
$types .= 's';
}
if (!empty($department)) {
$where[] = "department LIKE ?";
$params[] = "%$department%";
$types .= 's';
}
// 将WHERE条件数组组合成字符串
$whereClause = '';
if (!empty($where)) {
$whereClause = 'WHERE ' . implode(' AND ', $where);
}
// --- 4. 获取总记录数(用于分页计算)
$countSql = "SELECT COUNT(*) as total FROM student $whereClause";
$countStmt = $conn->prepare($countSql);
// 如果有查询条件,则绑定参数
if (!empty($params)) {
$countStmt->bind_param($types, ...$params);
}
$countStmt->execute();
$result = $countStmt->get_result();
$row = $result->fetch_assoc();
$totalRecords = $row['total'];
$totalPages = ceil($totalRecords / $pageSize);
// --- 5. 获取当前页的数据
$sql = "SELECT S_id, S_student, department FROM student $whereClause ORDER BY S_id LIMIT ?, ?";
$stmt = $conn->prepare($sql);
// 绑定参数
if (!empty($params)) {
$params[] = $pageSize;
$params[] = $offset;
$types .= 'ii';
$stmt->bind_param($types, ...$params);
} else {
$stmt->bind_param('ii', $pageSize, $offset);
}
$stmt->execute();
$result = $stmt->get_result();
// --- 6. 定义一个辅助函数,用于构建带查询条件的URL
function buildQueryString($page) {
$params = [];
if (!empty($_GET['s_id'])) $params[] = 's_id=' . urlencode($_GET['s_id']);
if (!empty($_GET['s_student'])) $params[] = 's_student=' . urlencode($_GET['s_student']);
if (!empty($_GET['department'])) $params[] = 'department=' . urlencode($_GET['department']);
$params[] = 'page=' . $page;
return implode('&', $params);
}
// --- 7. 关闭数据库连接
$conn->close();
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>学生信息查询系统 (ex5.php)</title>
<style>
body { font-family: 'Microsoft YaHei', Arial, sans-serif; margin: 20px; background-color: #f4f4f9; }
.container { max-width: 1000px; margin: 0 auto; background-color: #fff; padding: 25px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
h1 { color: #333; text-align: center; margin-bottom: 30px; }
.search-form { background-color: #f8f9fa; padding: 20px; border-radius: 5px; margin-bottom: 25px; border-left: 5px solid #007bff; }
.form-group { margin-bottom: 15px; display: flex; align-items: center; }
label { display: inline-block; width: 80px; font-weight: bold; color: #555; }
input[type="text"] { padding: 10px; width: 250px; border: 1px solid #ccc; border-radius: 4px; font-size: 14px; }
button { background-color: #007bff; color: white; padding: 10px 20px; border: none; border-radius: 4px; cursor: pointer; font-size: 14px; transition: background-color 0.3s; }
button:hover { background-color: #0056b3; }
.reset-btn { background-color: #6c757d; margin-left: 10px; }
.reset-btn:hover { background-color: #5a6268; }
table { width: 100%; border-collapse: collapse; margin-top: 20px; }
th, td { border: 1px solid #ddd; padding: 12px; text-align: left; }
th { background-color: #007bff; color: white; font-weight: bold; }
tr:nth-child(even) { background-color: #f2f2f2; }
tr:hover { background-color: #e9ecef; }
.pagination { margin-top: 20px; text-align: center; }
.pagination a, .pagination span { display: inline-block; padding: 8px 16px; margin: 0 4px; text-decoration: none; border: 1px solid #ddd; border-radius: 4px; transition: background-color 0.3s; }
.pagination a:hover { background-color: #e9ecef; }
.pagination .current { background-color: #007bff; color: white; border-color: #007bff; font-weight: bold; }
.no-results { text-align: center; padding: 30px; color: #6c757d; font-size: 16px; }
.info { margin-bottom: 20px; color: #495057; font-size: 15px; }
</style>
</head>
<body>
<div class="container">
<h1>学生信息查询系统</h1>

<!-- 查询表单 -->
<form method="GET" action="" class="search-form">
<div class="form-group">
<label for="s_id">学号:</label>
<input type="text" id="s_id" name="s_id" value="<?php echo htmlspecialchars($s_id); ?>" placeholder="请输入学号">
</div>
<div class="form-group">
<label for="s_student">姓名:</label>
<input type="text" id="s_student" name="s_student" value="<?php echo htmlspecialchars($s_student); ?>" placeholder="请输入姓名">
</div>
<div class="form-group">
<label for="department">院系:</label>
<input type="text" id="department" name="department" value="<?php echo htmlspecialchars($department); ?>" placeholder="请输入院系">
</div>
<div class="form-group">
<button type="submit">查询</button>
<button type="button" class="reset-btn" onclick="clearForm()">重置</button>
</div>
</form>
<!-- 查询结果 -->
<?php if ($totalRecords > 0): ?>
<div class="info">
共找到 <strong><?php echo $totalRecords; ?></strong> 条记录,当前显示第 <strong><?php echo $page; ?></strong> 页,共 <strong><?php echo $totalPages; ?></strong> 页
</div>
<table>
<thead>
<tr>
<th>序号</th>
<th>学号</th>
<th>姓名</th>
<th>院系</th>
</tr>
</thead>
<tbody>
<?php
$serial = $offset + 1; // 计算当前页的起始序号
while ($row = $result->fetch_assoc()):
?>
<tr>
<td><?php echo $serial++; ?></td>
<td><?php echo htmlspecialchars($row['S_id']); ?></td>
<td><?php echo htmlspecialchars($row['S_student']); ?></td>
<td><?php echo htmlspecialchars($row['department']); ?></td>
</tr>
<?php endwhile; ?>
</tbody>
</table>

<!-- 分页导航 -->
<?php if ($totalPages > 1): ?>
<div class="pagination">
<?php if ($page > 1): ?>
<a href="?<?php echo buildQueryString(1); ?>">首页</a>
<a href="?<?php echo buildQueryString($page - 1); ?>">上一页</a>
<?php endif; ?>

<?php
// 智能显示页码
$startPage = max(1, $page - 2);
$endPage = min($totalPages, $page + 2);
if ($startPage > 1) echo '<span>...</span>';

for ($i = $startPage; $i <= $endPage; $i++):
if ($i == $page):
echo '<span class="current">' . $i . '</span>';
else:
echo '<a href="?'.buildQueryString($i).'">'.$i.'</a>';
endif;
endfor;

if ($endPage < $totalPages) echo '<span>...</span>';
?>

<?php if ($page < $totalPages): ?>
<a href="?<?php echo buildQueryString($page + 1); ?>">下一页</a>
<a href="?<?php echo buildQueryString($totalPages); ?>">末页</a>
<?php endif; ?>
</div>
<?php endif; ?>
<?php else: ?>
<div class="no-results">
<?php if (!empty($s_id) || !empty($s_student) || !empty($department)): ?>
没有找到符合条件的学生记录。
<?php else: ?>
暂无学生数据,请先在数据库中插入数据。
<?php endif; ?>
</div>
<?php endif; ?>
</div>

<script>
// 重置表单并刷新页面
function clearForm() {
// 清空输入框
document.getElementById('s_id').value = '';
document.getElementById('s_student').value = '';
document.getElementById('department').value = '';
// 刷新页面,清除URL中的参数
window.location.href = 'ex5.php';
}
</script>
</body>
</html>

实验六:PHP和Ajax技术

实验目的

  1. 掌握AJAX的工作原理
  2. 掌握PHP中实现AJAX的过程和方法

实验内容

由用户指定查询条件,使用AJAX技术,在PHP网页中实现数据库查询操作代码部分的响应刷新

实验代码

ex6_1.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>院系学生信息查询</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
body { font-family: 'Microsoft YaHei', sans-serif; margin: 20px; background-color: #f9f9f9; }
.container { max-width: 800px; margin: 0 auto; background-color: #fff; padding: 20px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
h2 { color: #333; text-align: center; }
label { font-weight: bold; }
table { width: 100%; margin-top: 20px; border-collapse: collapse; }
th, td { padding: 12px; border: 1px solid #ddd; text-align: center; }
th { background-color: #4CAF50; color: white; }
tr:nth-child(even) { background-color: #f2f2f2; }
#loading { text-align: center; color: #888; display: none; }
.no-data { text-align: center; color: #888; }
</style>
</head>
<body>
<div class="container">
<h2>院系学生信息查询</h2>
<div>
<label for="departmentSelect">请指定院系:</label><br>
<select id="departmentSelect">
<option value="">-- 请选择院系 --</option>
<?php
$servername = "localhost";
$username = "ex6";
$password = "admin123"; // 请修改为您的密码
$dbname = "ex6";

$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("数据库连接失败: " . $conn->connect_error);
}

$sql = "SELECT DISTINCT department FROM student ORDER BY department";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<option value='" . htmlspecialchars($row["department"]) . "'>" . htmlspecialchars($row["department"]) . "</option>";
}
}
$conn->close();
?>
</select>
</div>

<div id="loading">正在加载数据...</div>

<table id="studentTable">
<thead>
<tr>
<th>学号</th>
<th>姓名</th>
<th>院系</th>
</tr>
</thead>
<tbody id="studentTableBody">
<tr>
<td colspan="3" class="no-data">请从上方菜单选择一个院系</td>
</tr>
</tbody>
</table>
</div>

<script>
$(document).ready(function(){
$("#departmentSelect").change(function(){
var selectedDept = $(this).val();
if (selectedDept === "") {
$("#studentTableBody").html('<tr><td colspan="3" class="no-data">请从上方菜单选择一个院系</td></tr>');
return;
}

$("#loading").show();
$("#studentTableBody").hide();

// 核心:确保AJAX请求正确发送了'department'参数
$.ajax({
url: "ex6_2.php",
type: "GET",
data: { department: selectedDept }, // <--- 检查这里
dataType: "json",
success: function(response){
var htmlContent = "";
if (response.success && response.data.length > 0) {
$.each(response.data, function(index, student){
htmlContent += "<tr>";
htmlContent += "<td>" + student.S_id + "</td>";
htmlContent += "<td>" + student.S_student + "</td>";
htmlContent += "<td>" + student.department + "</td>";
htmlContent += "</tr>";
});
} else {
htmlContent = '<tr><td colspan="3" class="no-data">该院系暂无学生信息</td></tr>';
}

$("#studentTableBody").html(htmlContent);
$("#loading").hide();
$("#studentTableBody").fadeIn();
},
error: function(jqXHR, textStatus, errorThrown){
console.error("AJAX Error: ", textStatus, errorThrown);
$("#loading").hide();
$("#studentTableBody").fadeIn();
}
});
});
});
</script>
</body>
</html>

ex6_2.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<?php
header('Content-Type: application/json; charset=utf-8');
$servername = "localhost";
$username = "ex6";
$password = "admin123"; // 请修改为您的密码
$dbname = "ex6";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
echo json_encode(['success' => false, 'message' => '数据库连接失败: ' . $conn->connect_error]);
exit();
}
// 增强的参数检查
if (isset($_GET['department']) && !empty(trim($_GET['department']))) {
$department = $conn->real_escape_string($_GET['department']);

$sql = "SELECT S_id, S_student, department FROM student WHERE department = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $department);
$stmt->execute();
$result = $stmt->get_result();

$students = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$students[] = $row;
}
echo json_encode(['success' => true, 'data' => $students]);
} else {
echo json_encode(['success' => true, 'data' => []]);
}
$stmt->close();
} else {
// 返回更明确的错误信息
echo json_encode(['success' => false, 'message' => '缺少院系参数或参数为空']);
}
$conn->close();
?>

以上内容由AI生成,仅供参考和借鉴