PHP第三十一篇——注册登录验证入门实战

实现处理PHP+MySQLi+HTML实战,简单到不能再简单的注册登录页面效果!

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
<?php

header('content-type:text/html;charset=utf-8');
##### 建立连接: 这里使用MAMP默认提供的mysql和端口
$link = mysqli_connect('localhost', 'root', 'root', 'mysqli','8889') or die('连接数据失败<\br>'.mysqli__connect_errno($link).':'.mysqli__connect_error($link));
//var_dump($link);
if (!$link) {
echo "错误连接";
echo 'ERROR'.mysqli_connect_errno().':'.mysqli_connect_error();
exit();
}

##### 设置字符集
mysqli_query($link, 'SET NAMES UTF8');

##### 打开指定数据库
$res = mysqli_select_db($link,'mysqli') or die('指定数据库不存在<\br>'.mysqli__errno($link).':'.mysqli__error($link));

```

### PHP操作请求

```bash
<?php

require_once 'connect.php';

$act = $_REQUEST['act'];

$username = $_POST['username'];
$password = $_POST['password'];

$regtime = time();

// 根据不同的操作完成不同的功能
switch ($act) {

case 'regist':
$sql = "INSERT user(username,password,regtime) VALUES('{$username}','{$password}','{$regtime}')";
$res = mysqli_query($link, $sql);
if ($res) {
echo "注册成功,恭喜发财, 第".mysqli_insert_id($link);
echo '<meta http-equiv="refresh" content="3;url=login.php"/>';
} else {
echo "注册失败,请先前往注册";
echo '<meta http-equiv="refresh" content="3;url=regist.php"/>';
}
break;

case 'login':
$sql = "SELECT * FROM user WHERE username='{$username}' AND password='{$password}'";
$res = mysqli_query($link, $sql);
if ($res && mysqli_num_rows($res)>0) {
echo "登录成功,恭喜发财, 第".mysqli_insert_id($link);
echo '<meta http-equiv="refresh" content="3;url=home.php"/>';
} else {
echo "登录失败,请重新登录";
echo '<meta http-equiv="refresh" content="3;url=login.php"/>';
}
break;

}

注册页面与简单逻辑:

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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>注册页面</title>
</head>
<body>
<h3>注册页面</h3>
<form action="doAction.php?act=regist" method="post">

<table border="1" width="80%" cellpadding="0" cellspacing="0" bgcolor="#ABCDEF">

<tr>
<td>用户名</td>
<td><input type="text" name="username" id="username" placeholder="请输入合法用户名"></td>
</tr>

<tr>
<td>密码</td>
<td><input type="text" name="password" id="password" placeholder="请输入密码"></td>
</tr>

<tr>
<td colspan="2">
<input type="submit" value="注册">
</td>
</tr>

</table>

</form>

</body>
</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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>登录页面</title>
</head>
<body>
<h3>登录页面</h3>
<form action="doAction.php?act=login" method="post">

<table border="1" width="80%" cellpadding="0" cellspacing="0" bgcolor="#ABCDEF">

<tr>
<td>用户名</td>
<td><input type="text" name="username" id="" placeholder="请输入合法用户名"></td>
</tr>

<tr>
<td>密码</td>
<td><input type="text" name="password" id="" placeholder="请输入密码"></td>
</tr>

<tr>
<td colspan="2">
<input type="submit" value="登录">
</td>
</tr>

</table>

</form>

</body>
</html>

首页展示:

1
2
3
4
5
6
7
8
9
10
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>首页</title>
</head>
<body>
<h3>首页</h3>
</body>
</html>

实战代码

以下是注册登录,验证PHP代码逻辑

index.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="en">
<head>
<meta charset="UTF-8" />
<title>梦工厂系统</title>
<script type="text/javascript" src="js/jquery-1.9.0.min.js"></script>
<script type="text/javascript" src="js/login.js"></script>
<link href="css/login.css" rel="stylesheet" type="text/css" />
</head>
<body>
<h1>
登陆注册系统<sup>V2016</sup>
</h1>

<div class="login" style="margin-top: 50px;">
<div class="header">
<div class="switch" id="switch">
<a class="switch_btn_focus" id="switch_qlogin"
href="javascript:void(0);" tabindex="7">快速登录</a> <a
class="switch_btn" id="switch_login" href="javascript:void(0);"
tabindex="8">快速注册</a>
<div class="switch_bottom" id="switch_bottom"
style="position: absolute; width: 64px; left: 0px;"></div>
</div>
</div>
<div class="web_qr_login" id="web_qr_login"
style="display: block; height: 235px;">

<!--登录-->
<div class="web_login" id="web_login">
<div class="login-box">
<div class="login_form">
<!-- 表单操作 -->
<form action="doAction.php?act=login" name="loginform"
accept-charset="utf-8" id="login_form" class="loginForm"
method="post">
<input type="hidden" name="did" value="0" /> <input type="hidden"
name="to" value="log" />
<div class="uinArea" id="uinArea">
<label class="input-tips" for="u">帐号:</label>
<div class="inputOuter" id="uArea">
<input type="text" id="u" name="username" class="inputstyle" />
</div>
</div>
<div class="pwdArea" id="pwdArea">
<label class="input-tips" for="p">密码:</label>
<div class="inputOuter" id="pArea">

<input type="password" id="p" name="password" class="inputstyle" />
</div>
</div>
<div style="padding-left: 50px; margin-top: 20px;">
<input type="submit" value="登 录" style="width: 150px;"
class="button_blue" />
</div>
</form>
</div>
</div>
</div>
<!--登录end-->

</div>

<!--注册-->
<div class="qlogin" id="qlogin" style="display: none;">
<div class="web_login">
<!-- 表单操作 -->
<form name="form2" id="regUser" accept-charset="utf-8"
action="doAction.php?act=reg" method="post">
<input type="hidden" name="to" value="reg" /> <input type="hidden"
name="did" value="0" />
<ul class="reg_form" id="reg-ul">
<div id="userCue" class="cue">快速注册请注意格式</div>
<li><label for="user" class="input-tips2">用户名:</label>
<div class="inputOuter2">
<input type="text" id="user" name="username" maxlength="16"
class="inputstyle2" />
</div>
</li>
<li><label for="passwd" class="input-tips2">密码:</label>
<div class="inputOuter2">
<input type="password" id="passwd" name="password" maxlength="16"
class="inputstyle2" />
</div>
</li>
<li><label for="passwd2" class="input-tips2">确认密码:</label>
<div class="inputOuter2">
<input type="password" id="passwd2" name="password2" maxlength="16"
class="inputstyle2" />
</div>
</li>

<li><label for="email" class="input-tips2">邮箱:</label>
<div class="inputOuter2">
<input type="email" id="email" name="email" class="inputstyle2" />
</div>
</li>
<li>
<div class="inputArea">
<input type="button" id="reg"
style="margin-top: 10px; margin-left: 85px;"
class="button_blue" value="同意协议并注册" /> <a href="#" class="zcxy"
target="_blank">注册协议</a>
</div>
</li>
<div class="cl"></div>
</ul>
</form>
</div>
</div>
<!--注册end-->

</div>
</body>
</body>
</html>
login.css
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
227
228
229
230
231
232
233
234
235
236
237
238
239
html {

}
body {
font-family:"Microsoft Yahei";
font-size:12px;
margin:0;
background: #fff url(../images/1.jpg) 50% 0 no-repeat;}
ul {
padding:0;
margin:0;
}
ul li {
list-style-type:none;
}
a {
text-decoration:none;
}
a:hover {
text-decoration:none;color:#f00;
}
.cl{ clear: both;}
input[type="text"]:focus, input[type="password"]:focus {
outline:none;
}
input::-ms-clear {
display:none;
}
.login {
margin:0 auto;
width:370px;
border:2px solid #eee;
border-bottom:none;
position:relative;
}
.header {
height:50px;
border-bottom:1px solid #e2e2e2;
position:relative;
font-family:"Microsoft Yahei";
}
.header .switch {
height:45px;
position:absolute;
left:60px;
bottom:0;
font-size:16px;
}
.header .switch #switch_qlogin {
margin-right:85px;
}
.header .switch .switch_btn {
color:#999;
display:inline-block;
height:45px;
line-height:45px;
outline:none;
*hide-focus:expression(this.hideFocus=true);
}
.header .switch .switch_btn_focus {
color:#333;
display:inline-block;
height:45px;
line-height:45px;
outline:none;
*hide-focus:expression(this.hideFocus=true);
}
.header .switch .switch_btn:hover {
color:#333;
text-decoration:none;
}
.header .switch .switch_btn_focus:hover {
text-decoration:none;
}
#switch_bottom {
position:absolute;
bottom:-1px;_bottom:-2px;
border-bottom:2px solid #848484;
}

.web_login {
width:370px;
position:relative;
}
#web_login{_left:60px;*left:0;}
.web_login .login_form {
width:272px;
margin:0 auto;
}
.web_login .reg_form {
width:300px;
margin:0 auto;
}
.web_login .input-tips {
float:left;
margin-top:10px;
width:50px;
height:42px;
font-size:16px;
line-height:42px;
font-family:"Hiragino Sans GB", "Microsoft Yahei";
}
.web_login .input-tips2 {
float:left;
text-align:right;
padding-right:10px;
width:75px;
height:30px;
font-size:16px;
margin-top:10px;
clear:both;
line-height:30px;
font-family:"Hiragino Sans GB", "Microsoft Yahei";
}
.web_login .inputOuter {
width:200px;
height:42px;
margin-top:10px;
float:left;

}
.web_login .inputOuter2 {
width:200px;
margin-top:6px;margin-top:5px\9;
float:left;

}
.web_login .inputstyle {
width:200px;
height:38px;
padding-left:5px;
line-height:30px;line-height:38px;
border:1px solid #D7D7D7;
background:#fff;
color:#333;border-radius:2px;
font-family:Verdana, Tahoma, Arial;
font-size:16px;
ime-mode:disabled;
}
.web_login input.inputstyle2:focus,.web_login input.inputstyle:focus{border:1px solid #198BD4;box-shadow:0 0 2px #198BD4;}
.web_login .inputstyle2 {
width:200px;
height:34px;
padding-left:5px;
line-height:34px;
border:1px solid #D7D7D7;
background:#fff;
color:#333;border-radius:2px;
font-family:Verdana, Tahoma, Arial;
font-size:16px;
ime-mode:disabled;
}
.web_login .uinArea {
height:55px;
position:relative;
z-index:10;
}
.web_login .pwdArea {
height:55px;
margin-bottom:10px;
position:relative;
z-index:3;
}
.web_qr_login {
position:relative;

overflow:hidden;
}

.cue {
height:40px;
line-height:40px;
font-size:14px;
border:1px #CCCCCC solid;
margin-top:10px;margin-bottom:5px;
text-align:center;
font-family:"Hiragino Sans GB", "Microsoft Yahei";
}
.login {
background-color:#ffffff;
}

h1{margin:80px auto 50px auto;text-align:center;color:#fff;margin-left:-25px;font-size:35px;font-weight: bold;text-shadow: 0px 1px 1px #555;}
h1 sup{
font-size: 18px;
font-style: normal;
position: absolute;
margin-left: 10px;}
.login {border:0;padding:5px 0;
background: #fff;
margin: 0 auto;
-webkit-box-shadow: 1px 1px 2px 0 rgba(0, 0, 0, .3);
box-shadow: 1px 1px 2px 0 rgba(0, 0, 0, .3);}

.web_login{padding-bottom:20px;}

.jianyi{color:#fff;text-align:center;margin-top:25px;color:#B3B8C4;}
.reg_form li {
height: 55px;
}
.cue {
margin-top: 15px;
margin-bottom: 10px;border:1px solid #eee;border-radius:3px;
}
.web_login input.inputstyle2:focus, .web_login input.inputstyle:focus {
border: 1px solid #5796f;
box-shadow: 0 0 0;
}
.web_login .reg_form {
width: 300px;
margin: 0 auto;
}
.web_login .inputstyle2 {border-radius:2px;width:210px;}
.web_login .input-tips2 {
padding-right: 5px;
width: 80px;_width: 75px;_font-size:12px;}
.button_blue
{
display:inline-block;
float:left;
height:41px;border-radius:4px;
background:#2795dc;border:none;cursor:pointer;
border-bottom:3px solid #0078b3;*border-bottom:none;
color:#fff;
font-size:16px;padding:0 10px;*width:140px;
text-align:center;outline:none;font-family: "Microsoft Yahei",Arial, Helvetica, sans-serif;
}
input.button_blue:hover
{
background:#0081c1;
border-bottom:3px solid #006698;*border-bottom:none;
color:#fff;
text-decoration:none;
}
a.zcxy {text-decoration: underline;line-height:58px;margin-left:15px;color: #959ca8;}
.web_login .login_form {margin-top:30px;}
.web_login .uinArea {
height: 60px;}
.header .switch{left:70px;}
login.js
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
$(function() {
$('#switch_qlogin').click(
function() {
$('#switch_login').removeClass("switch_btn_focus").addClass(
'switch_btn');
$('#switch_qlogin').removeClass("switch_btn").addClass(
'switch_btn_focus');
$('#switch_bottom').animate({
left : '0px',
width : '70px'
});
$('#qlogin').css('display', 'none');
$('#web_qr_login').css('display', 'block');
});
$('#switch_login').click(
function() {
$('#switch_login').removeClass("switch_btn").addClass(
'switch_btn_focus');
$('#switch_qlogin').removeClass("switch_btn_focus").addClass(
'switch_btn');
$('#switch_bottom').animate({
left : '154px',
width : '70px'
});
$('#qlogin').css('display', 'block');
$('#web_qr_login').css('display', 'none');
});
if (getParam("a") == '0') {
$('#switch_login').trigger('click');
}
});
function logintab(){
scrollTo(0);
$('#switch_qlogin').removeClass("switch_btn_focus").addClass('switch_btn');
$('#switch_login').removeClass("switch_btn").addClass('switch_btn_focus');
$('#switch_bottom').animate({left:'154px',width:'96px'});
$('#qlogin').css('display','none');
$('#web_qr_login').css('display','block');
}
//根据参数名获得该参数 pname等于想要的参数名
function getParam(pname) {
var params = location.search.substr(1); // 获取参数 平且去掉?
var ArrParam = params.split('&');
if (ArrParam.length == 1) {
//只有一个参数的情况
return params.split('=')[1];
}
else {
//多个参数参数的情况
for (var i = 0; i < ArrParam.length; i++) {
if (ArrParam[i].split('=')[0] == pname) {
return ArrParam[i].split('=')[1];
}
}
}
}
var reMethod = "GET",
pwdmin = 6;
$(document).ready(function() {
$('#user').blur(function(){
$.ajax({
type: reMethod,
url: "doAction.php?act=checkUser",
data: "username=" + $("#user").val(),
dataType: 'html',
success: function(result) {
if (result==1) {
$('#user').focus().css({
border: "1px solid red",
boxShadow: "0 0 2px red"
});
$("#userCue").html('用户名已存在!');
return false;
} else {
$('#user').css({
border: "1px solid #D7D7D7",
boxShadow: "none"
});
}
}
});
});

$('#reg').click(function() {
if ($('#user').val() == "") {
$('#user').focus().css({
border: "1px solid red",
boxShadow: "0 0 2px red"
});
$('#userCue').html("<font color='red'><b>×用户名不能为空</b></font>");
return false;
}
if ($('#user').val().length < 4 || $('#user').val().length > 16) {
$('#user').focus().css({
border: "1px solid red",
boxShadow: "0 0 2px red"
});
$('#userCue').html("<font color='red'><b>×用户名位4-16字符</b></font>");
return false;
}
if ($('#passwd').val().length < pwdmin) {
$('#passwd').focus();
$('#userCue').html("<font color='red'><b>×密码不能小于" + pwdmin + "位</b></font>");
return false;
}
if ($('#passwd2').val() != $('#passwd').val()) {
$('#passwd2').focus();
$('#userCue').html("<font color='red'><b>×两次密码不一致!</b></font>");
return false;
}
var reg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;
if (!reg.test($('#email').val())) {
$('#email').focus().css({
border: "1px solid red",
boxShadow: "0 0 2px red"
});
$('#userCue').html("<font color='red'><b>×email格式不正确</b></font>");return false;
} else {
$('#email').css({
border: "1px solid #D7D7D7",
boxShadow: "none"
});
}
$('#regUser').submit();
});
});
doAction.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
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
<?php 
header('content-type:text/html;charset=utf-8');

//基础引入
require_once 'functions/mysql.func.php';
require_once 'config/config.php';
//邮件发送库
require_once 'swiftmailer-master/lib/swift_required.php';

require_once 'functions/common.func.php';

//接受信息
$act = $_REQUEST['act']; // 请求跳转操作
$username = $_POST['username']; // 用户名
$password = $_POST['password']; // 密码

$link = connect3(); // 连接数据库

$table = 'maizi_user';

// 根据用户不同操作执行不同功能
switch ($act) {

case 'reg':

// 事务操作
// 1.关闭自动提交
mysqli_autocommit($link, FALSE);

// 用户输入加产生数据
$email = $_POST['email'];
$reg_time = time();
$token = md5($username.$password.$reg_time); // 生成Token
$token_exptime = $reg_time+24*3600; // Token过期时间
$status = 1; // Token过期时间
$data = compact("username", "password","email","reg_time","token","token_exptime","status");

// 插入数据
$res_insert = insert($link, $data, $table);
if ($res_insert) {
mysqli_commit($link);
mysqli_autocommit($link, TRUE);
echo "<script>alert('注册成功,立即登录');location.href='index.php'</script>";
//alertMessage('注册成功,立即登录', 'index.php');
} else {
mysqli_rollback($link);
echo "<script>alert('注册失败,重新注册');location.href='index.php'</script>";
//alertMessage('注册失败,重新注册', 'index.php');
}
break;

// ================================== 发送邮件: 存在问题, 待调试 ==================================
// 1. 初始化邮件服务器对象
$transport = Swift_SmtpTransport::newInstance('smtp.qq.com', 25);
// 设置邮箱信息
$transport->setUsername(Mail_Name);
$transport->setUsername(Mail_PWD);

// 发送邮件对象
$mailer = Swift_Mailer::newInstance($transport);

// ================= 消息对象: 发件人,收件人,设置主题和内天 =================
$message = Swift_Message::newInstance();
//发件人
$message->setFrom(array(Mail_Name));
//收件人
$message->setTo(array($email));

//主题
$message->setSubject("【梦工厂@iCocos】注册账号激活主题");
//内容
$actStr = "?act=active&username={$username}&token={$token}";
$url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'].$actStr;
$urlEncode = urlencode($url);
$messageBody = <<<EOF
尊敬的梦工厂用户,您好:
账号 {$email} ,注册并创建成功,请点击并激活, 前往主页, 详情如下:
<a href='{$url}' target='_blank'>{$urlEncode}</a>
(该链接24小时内有效)
感谢您使用梦工厂,如果您在使用过程中有任何疑问,请参见下方提交工单联系我们。
谢谢!
EOF;

$message->setBody($messageBody, "text/html",'utf-8');

// 附件
$path = "images/maizi.png";
$message->attach(Swift_Attachment::fromPath($path, 'image/png'));

// 发送操作
try {
$mail_res = $mailer->send($message);
if ($mail_res && $res_insert) {
mysqli_commit($link);
mysqli_autocommit($link, TRUE);
echo "<script>alert('注册成功,立即登录');location.href='index.php'</script>";
} else {
mysqli_rollback($link);
echo "<script>alert('注册失败,重新注册');location.href='index.php'</script>";
}
} catch (Swift_ConnectionException $e) {
die("邮件服务器错误") . $e->getMessage();
}
// ================================== 发送邮件 ==================================
break;

case 'login': // 用户登录操作
$username = addslashes($username);
$sql = "SELECT id, status FROM {$table} WHERE username='{$username}' AND password='{$password}'";
$user = fetchOne($link, $sql);
if ($user) {
if ($user['status'] == 0) {
echo "<script>alert('请先激活,再登录');location.href='index.php'</script>";
} else {
echo "<script>alert('登录成功');location.href='index.php'</script>";
}
} else {
echo "<script>alert('用户名密码错误');location.href='index.php'</script>";
}
break;

case 'active': // 邮箱邮件外链激活操作
// http://com.mysqli.php:8888/logregmail/doAction.php
// act=active&username=sdsds&token=ec821fcf18762a8cce7df5c47874b2f4
echo "点击邮件连接,跳转并激活成功,设置表status状态为1";
$token = $_POST['token']; // token
$username = mysqli_real_escape_string($link, $username);
$query = "SELECT id, token_exptime FROM {$table} WHERE username='{$username}'";
$user = fetchOne($link, $query);
if ($user) {
// 检查是否超时
$now = time();
$token_exptime = $user['token_exptime'];
if ($now>$token_exptime) {
// 清空用户
delete($link, $table, "username='{$username}'");
echo "<script>alert('激活码无效,或者过期,请重新注册!!!');location.href='index.php'</script>";
} else {
// 激活操作:update-ststus
$data=array('status'=>1);
$update = update($link, $data, $table, "username='{$username}'");
if ($update) {
echo "<script>alert('激活成功, 立即登录');location.href='index.php'</script>";
} else {
echo "<script>alert('激活失败,请重新激活!');location.href='index.php'</script>";
}
}
} else {
echo "<script>alert('激活失败,没有找到要激活的用户!!!');location.href='index.php'</script>";
}

break;
case 'checkUser': // Ajax用户注册状态检测
$username = mysqli_real_escape_string($link, $username);
$query = "SELECT id FROM {$table} WHERE username='{$username}'";
$user = fetchOne($link, $query);
if ($user) {
return 1;
} else {
return 0;
}
break;
default:
die("非法操作");
break;
}
config.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?php

$config=[
'host'=>'localhost',
'user'=>'root',
'password'=>'root',
'charset'=>'utf8',
'dbName'=>'maizi',
'dbPort'=>'8889'
];

define('DB_HOST','localhost');
define('DB_USER','root');
define('DB_PWD','root');
define('DB_CHARSET','utf8');
define('DB_DBNAME','maizi');
define('DB_PORT','8889');


define('Mail_Name','2211523681@qq.com');
define('Mail_PWD','???????');
mysql.func.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
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
<?php
/**
* 连接
* @param string $host
* @param string $user
* @param string $password
* @param string $charset
* @param string $database
* @return object 连接标识符
*/
function connect1($host,$user,$password,$charset,$database) {
$link = mysqli_connect ( $host, $user, $password ) or die ( '数据库连接失败<br/>ERROR ' . mysqli_connect_errno () . ':' . mysqli_connect_error () );
mysqli_set_charset ( $link, $charset );
mysqli_select_db ( $link, $database ) or die ( '指定数据库打开失败<br/>ERROR ' . mysqli_errno ( $link ) . ':' . mysqli_error ( $link ) );
return $link;
}
/**
* 连接 需要传递数组
* @param array $config
* @return object
*/
function connect2($config) {
$link = mysqli_connect ( $config ['host'], $config ['user'], $config ['password'] ) or die ( '数据库连接失败<br/>ERROR ' . mysqli_connect_errno () . ':' . mysqli_connect_error () );
mysqli_set_charset ( $link, $config ['charset'] );
mysqli_select_db ( $link, $config ['dbName'] ) or die ( '指定数据库打开失败<br/>ERROR ' . mysqli_errno ( $link ) . ':' . mysqli_error ( $link ) );
return $link;
}
/**
* 用常量的形式建立连接
* @return unknown
*/
function connect3(){
$link = mysqli_connect ( DB_HOST, DB_USER, DB_PWD, DB_DBNAME, DB_PORT ) or die ( '数据库连接失败<br/>ERROR ' . mysqli_connect_errno () . ':' . mysqli_connect_error () );
mysqli_set_charset ( $link, DB_CHARSET );
mysqli_select_db ( $link, DB_DBNAME ) or die ( '指定数据库打开失败<br/>ERROR ' . mysqli_errno ( $link ) . ':' . mysqli_error ( $link ) );
return $link;
}

/*
array(
'username'=>'king',
'password'=>'king',
'age'=>'12',
'regTime'=>'123123123'
);
INSERT user(username,password,age,regTime) VALUES('king','king','12','123123123');
*/
/**
* 插入操作
* @param object $link
* @param array $data
* @param string $table
* @return boolean
*/
function insert($link,$data,$table){
$keys = join ( ',', array_keys ( $data ) );
$vals = "'" . join ( "','", array_values ( $data ) ) . "'";
$query = "INSERT {$table}({$keys}) VALUES({$vals})";
$res = mysqli_query ( $link, $query );
if ($res) {
return mysqli_insert_id ( $link );
} else {
return false;
}
}

/*
array(
'username'=>'king123',
'password'=>'king123',
'age'=>'32',
'regTime'=>'123123123'
);
UPDATE user SET username='king123',password='king123',age='32',regTime='123123123' WHERE id=1
*/
/**
* 更新操作
* @param object $link
* @param array $data
* @param string $table
* @param string $where
* @return boolean
*/
function update($link, $data, $table, $where = null) {
foreach ( $data as $key => $val ) {
$set .= "{$key}='{$val}',";
}
$set = trim ( $set, ',' );
$where = $where == null ? '' : ' WHERE ' . $where;
$query = "UPDATE {$table} SET {$set} {$where}";
$res = mysqli_query ( $link, $query );
if ($res) {
return mysqli_affected_rows ( $link );
} else {
return false;
}
}

//DELETE FROM user WHERE id=
/**
* 删除操作
* @param object $link
* @param string $table
* @param string $where
* @return boolean
*/
function delete($link, $table, $where = null) {
$where = $where ? ' WHERE ' . $where : '';
$query = "DELETE FROM {$table} {$where}";
$res = mysqli_query ( $link, $query );
if ($res) {
return mysqli_affected_rows ( $link );
} else {
return false;
}
}

/**
* 查询指定记录
* @param object $link
* @param string $query
* @param string $result_type
* @return array|boolean
*/
function fetchOne($link, $query, $result_type = MYSQLI_ASSOC) {
$result = mysqli_query ( $link, $query );
if ($result && mysqli_num_rows ( $result ) > 0) {
$row = mysqli_fetch_array ( $result, $result_type );
return $row;
} else {
return false;
}
}

/**
* 查询所有记录
* @param object $link
* @param string $query
* @param string $result_type
* @return array|boolean
*/
function fetchAll($link, $query, $result_type = MYSQLI_ASSOC) {
$result = mysqli_query ( $link, $query );
if ($result && mysqli_num_rows ( $result ) > 0) {
while ( $row = mysqli_fetch_array ( $result, $result_type ) ) {
$rows [] = $row;
}
return $rows;
} else {
return false;
}
}

/**
* 得到表中的记录数
* @param object $link
* @param string $table
* @return number|boolean
*/
function getTotalRows($link, $table) {
$query = "SELECT COUNT(*) AS totalRows FROM {$table}";
$result = mysqli_query ( $link, $query );
if ($result && mysqli_num_rows ( $result ) == 1) {
$row = mysqli_fetch_assoc ( $result );
return $row ['totalRows'];
} else {
return false;
}
}

/**
* 得到结果集的记录条数
* @param object $link
* @param string $query
* @return boolean
*/
function getResultRows($link, $query) {
$result = mysqli_query ( $link, $query );
if ($result) {
return mysqli_num_rows ( $result );
} else {
return false;
}
}

/**
* @param object $link
*/
function getServerInfo($link) {
return mysqli_get_server_info ( $link );
}
/**
* @param object $link
*/
function getClientInfo($link) {
return mysqli_get_client_info ( $link );
}

/**
* @param object $link
*/
function getHostInfo($link){
return mysqli_get_host_info($link);
}

/**
* @param object $link
*/
function getProtoInfo($link) {
return mysqli_get_proto_info ( $link );
}

以上使用jquery-1.9.0.min.js实现JS基本功能交互,SwiftMailer实现用户邮箱验证,后期会根据实战抽一篇文章说关于邮箱和短信验证的实战!

笔记总结:

检测MySQLi扩展是否已经开启
  • phpinfo();
    • 检测MySQLi扩展是否已经加载,如果已经加载返回true,否则返回false
  • var_dump(extension_loaded(‘mysqli’));
    • Fatal error(致命错误): Call to undefined function mysqli_connect()
      in G:\maizi\PHPAdvance\MySQLi\1-mysqli_connect.php on line 6
  • function_exists():检测某个函数是否存在
    • var_dump(function_exists(‘mysqli_connect’));
  • print_r(get_defined_functions());
mysqli_multi_query
  • 执行多条SQL语句,每条SQL语句一定要以分号结尾,否则就会失败
  • 如果多条SQL语句中有一条失败了,整个都会失败
结果集
  • mysqli_store_result():传输上一次产生的结果集
  • mysqli_more_results():判读是否有更多的结果集
  • mysqli_next_result():将结果集的指针向下移动一位
错误信息与编号
  • mysqli_connect_errno():连接产生的错误编号
  • mysqli_connect_error():连接产生的错误信息
  • mysqli_errno($link):得到上一步操作产生的错误编号
  • mysqli_error($link):得到上一步操作产生的错误信息
mysqli_query

mysqli_query($link,$sql):执行SQL查询

  • 1》只能执行一条SQL语句,SQL语句可以没有分号
  • 2》mysqli_query()执行SELECT/SHOW/EXPLAIN/DESC/DESCRIBE这样关键字的SQL语句,执行

成功返回的是mysqli_result结果集,执行失败返回false;

执行其他SQL语句,执行成功返回true,失败返回false

mysqli_affected_rows

mysqli_affected_rows($link):得到上一步操作产生的受影响的记录数

  • 大于0的:受影响的记录数
  • 等于0:没有记录被影响
  • 等于-1:代表的SQL语句有问题
result_type

$result_type的值为:

  • MYSQLI_BOTH:关联+索引
  • MYSQLI_ASSOC:关联
  • MYSQLI_NUM:索引
连接不成功的情况:
  • 1》用户名密码不正确

    • Warning: mysqli_connect(): (HY000/1045): Access denied for user ‘root‘@’localhost’ (using password: YES) in G:\maizi\PHPAdvance\MySQLi\2-mysqli_connect.php on line 5

bool(false)

  • 2》MySQL服务器没有开启

    • ERROR 2003 (HY000): Can’t connect to MySQL server on ‘localhost’ (10061)
      Warning: mysqli_connect(): in G:\maizi\PHPAdvance\MySQLi\2-mysqli_connect.php on line 13

bool(false)

防止SQL注入 : ‘ or 1=1
  1. 转义特殊字符
  2. 预处理
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
$username=addslashes($username);
$username=mysqli_real_escape_string($username);

$sql = "SELECT * FROM user WHERE username=? AND password=?";
$sql = "SELECT id,username,password FROM user WHERE username=? AND password=?";
if ($stmt=mysqli_prepare($link, $sql)) {
mysqli_stmt_bind_param($stmt, 'ss', $username, $password);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
echo "--------";
echo '</br>'.mysqli_stmt_affected_rows($stmt).'</br>';
echo mysqli_stmt_num_rows($stmt).'</br>';
echo "--------</br>";
if (mysqli_stmt_affected_rows($stmt) == 1) {
mysqli_stmt_bind_result($stmt,$id,$username,$password);
mysqli_stmt_reset($stmt);
echo "登录成功";
echo "</br>编号:".$id.'<br/>用户名:'.$username.'<br/>密码:'.$password;
}
}
坚持原创技术分享,您的支持将鼓励我继续创作!