Ajax+PHP+MySQL登陆示例
php是一门很好的语言,可以很方便的开发web应用程序,下面介绍一下PHP如何通过Ajax方式实现登录功能:
1 login.php登录界面中,javascript脚本用ajax方式异步请求dologin.php,dologin.php负责用户信息验证(包括验证码,php生成验证码可以自行搜索).登录界面的代码如下:
1<?phpsession_start();?>2<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">3<htmlxmlns="http://www.w3.org/1999/xhtml">4<head>5<metahttp-equiv="Content-Type"content="text/html; charset=gb2312"/>6<title>login</title>7<linkrel="stylesheet"type="text/CSS"href="CSS/login.css"/>8<scriptsrc="JS/ajaxhelper.js"type="text/Javascript"></script>9<scriptsrc="JS/jquery-1.3.2.min.js"type="text/javascript"></script>10<scripttype="text/javascript">11functionchkForm() {12if(m$('username').value=="") {1314alert('用户名不能为空.');15m$('username').focus();16returnfalse;1718}19if(m$('passWord').value=="") {2021alert('密码不能为空.');22m$('password').focus();23returnfalse;2425}26if(m$('password').value!=""&&m$('username').value!="") {2728varxmlhttp=createRequest();29if(xmlhttp) {30m$('loading').innerHTML="<font color='red'>loading...</font>";31varusername=m$('username').value;32varpwd=m$('password').value;33varcode=m$('txtCode').value;34varurl="dologin.php";35xmlhttp.open("POST", url,true);36xmlhttp.onreadystatechange=ValidateResult;37xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");38xmlhttp.send("username="+escape(username)+"&password="+escape(pwd)+"&code="+escape(code));3940}else{41alert('xmlHttp创建失败.');4243}4445functionValidateResult() {46if(xmlhttp.readyState==4) {47if(xmlhttp.status==200) {48if(xmlhttp.responseText!="") {4950//window.alert(xmlhttp.responseText);51varobj=eval("("+xmlhttp.responseText+")");52if(obj.result==true) {53alert("提示:"+obj.info);54window.location='index.php';5556}else{57alert("错误:"+obj.info);5859}60}else{61window.alert("从服务器获取失败");6263window.location.reload();64}65m$('loading').innerHTML="";66}67}6869}707172}7374}7576functionm$(id) {77returndocument.getElementById(id);78}7980functionchangeCode() {81varxmlhttp=createRequest();82if(xmlhttp) {83m$('loading').innerHTML="<font color='red'>loading...</font>";84vardt=newDate().getTime();85//alert(dt);86varurl="function/imagecode.php?dummay"+escape(dt);87xmlhttp.open("GET", url,true);88xmlhttp.onreadystatechange=ValidateResult;89xmlhttp.send(null);9091}else{92alert('xmlHttp创建失败.');9394}9596functionValidateResult() {97if(xmlhttp.readyState==4) {98if(xmlhttp.status==200) {99vardt=newDate().getTime();100varurl="function/imagecode.php?dummay"+escape(dt);101m$('imgCode').src="function/imagecode.php?dummay"+escape(dt);102m$('loading').innerHTML="";103}104}105106}107}108109functionshowTool() {110$('#divToolTip').css("display","block");111}112113functionhideTool() {114$('#divToolTip').css("display","none");115}116window.onload=initPage;117118functioninitPage() {119$('#divToolTip').css("display","none");120}121</script>122</head>123<body>124<divstyle="background-color:#2A3F55; height:80px;">125126</div>127<divstyle="min-height:500px;">128129<divclass="left">130131<divstyle="margin:120px auto auto auto; height:300px; text-align:left">132<divstyle="font-size:26px;color:#2A3F55; text-align:center;">Ajax PHP Demo System133<imgsrc="Images/appstorm-icon.png"alt="appcation storm image"style="position:relative;top:-18px; left:-12px; vertical-align:middle; text-align:center;font-size:10px; width:65px; height:46px;"/>134</div>135<
br/>136<hrstyle="border:dashed thin #2A3F55;width:70%; text-align:center;"/>137<divstyle="font-size:13px;color:#999999; margin:20px auto 0 auto; padding-left:200px;">138Author:<ahref="#"onmousemove="showTool();"onmouSEOut="hideTool();">wangming</a>139</div>140<divstyle="font-size:13px;color:#999999;margin:20px auto auto auto; padding-left:200px;">DateTime:2009-9-1</div>141<divstyle="font-size:13px;color:#999999;margin:20px auto auto auto; padding-left:200px;">Version:1.0.0</div>142<divstyle="font-size:13px;color:#999999;margin:20px auto auto auto; padding-left:200px;">Email:wangmingemail@163.com</div>143<divid="divToolTip">144<imgsrc="Images/ming.jpg"height="86px;"/>145<spanclass="authordes">146<
br/>147姓名:wangming<
br/>148电商06-2<
br/>149</span>150151</div>152153</div>154155</div>156157<divclass="right">158159<form>160<
br/>161<tableclass="flogin">162<tr>163<td>用户名:</td>164<td><inputtype="text"name="username"id="username"/></td>165<td></td>166</tr>167<tr>168<td>密 码:</td>169<td><inputtype="password"name="password"id="password"/></td>170<td></td>171</tr>172<tr>173<td>验证码:</td>174<td>175<inputtype="text"name="txtCode"id="txtCode"size="12"/> 176<imgsrc="function/imagecode.php"id="imgCode"alt="image code"height="22px;"style=" vertical-align:bottom;"/>177</td>178<td><inputtype="button"class="btnrefresh"onclick="changeCode();"/></td>179</tr>180<tr>181<td></td>182<td><inputtype="button"class="btnlogin"onclick="chkForm();"/></td>183<td></td>184</tr>185<tr>186<td></td>187<td><spanid="loading"></span></td>188<td><spanid="code"></span></td>189</tr>190191</table>192</form>193</div>194195</div>196<divstyle="background-color:#2A3F55; height:60px; margin:auto 0 0 0; clear:both; text-align:center; line-height:60px; color:#FFFFFF;font-size:12px;">197©Copyright 2015.198</div>199</body>200</html>
2 ajaxhelper.js1functioncreateRequest() {2try{3request =newXMLHttPRequest();4}catch(tryMS) {5try{6request =newActiveXObject("Msxml2.XMLHTTP");7}catch(otherMS) {8try{9request =newActiveXObject("Microsoft.XMLHTTP");10}catch(failed) {11request =null;12}13}14}15returnrequest;16}1718functiongetActivatedObject(e) {19varobj;20if(!e) {21//early version of IE22obj =window.event.srcElement;23}elseif(e.srcElement) {24//IE 7 or later25obj =e.srcElement;26}else{27//DOM Level 2 browser28obj =e.target;29}30returnobj;31}3233functionaddEventHandler(obj, eventName, handler) {34if(document.attachEvent) {35obj.attachEvent("on" +eventName, handler);36}elseif(document.addEventListener) {37obj.addEventListener(eventName, handler,false);38}39}
3dologin.php1<?php2session_start();3header("Content-type:text/html;charset=gb2312");//防止返回的中文乱码4$name=$_POST['username'];5$pwd=$_POST['password'];6$imagecode=$_POST['code'];7if(strtoupper($imagecode)==$_SESSION["code"])8{9include("conn/conn.php");10$sql="select studentName,studentPwd from tbstudent where studentId='".$name."'";11$result=MySQL_query($sql,$conn);12if($row=mysql_fetch_assoc($result))13{14if($pwd==$row['studentPwd'])15{16$_SESSION['username']=$row['studentName'];17//echo "{'result':true,'info':'登陆成功!','code':'".$_SESSION["code"]."'}";18echo"{'result':true,'info':'登陆成功!'}";1920}21else22{23echo"{'result':false,'info':'密码错误!'}";24}25}26else27{28echo"{'result':false,'info':'该用户不存在!'}";29}30}31else32{33echo"{'result':false,'info':'验证码错误!'}";34}35?>
4 conn.php1<?php2$conn=$mysql_connect("localhost","root", "");3mysql_select_db("bbs",$conn);4mysql_query("SET NAMES GB2312");5?>
5 user.php1<?php2classUsers {3functionUsers() {4}5functioncheckLogin($username,$userpwd) {6try{7mysql_connect("localhost", "root", "123");8mysql_select_db("studentdb");9mysql_query("SET NAMES GB2312");10$sql= "select userid from tbuser where username='$username' and userpwd='" .md5(trim($userpwd)) . "'";11$result=mysql_query($sql);12if($result) {13$arr=mysql_fetch_row($result);14$uid=$arr[0];15if($uid!= "") {16return"true|$uidlogin ok.$sql";17mysql_close();18}else{19return"false|login failed!$sql";20mysql_close();21}22}else{23return"false|$resultlink db failed!";24mysql_close();25}26}27catch(Exception$ex) {28return"false|$ex";29mysql_close();30}31}32functionAddUser($name,$pwd) {33try{34mysql_connect("localhost", "root", "123");35mysql_select_db("studentdb");36mysql_query("set names gb2312");37$sql0=mysql_query("select userid from tbuser where username='$name'");38$info0=mysql_fetch_array($sql0);39$userid=$info0[0];40if($info0!=false) {41return"false |$nameis exisis.(id:$userid)";42}43$pwd=md5(trim($pwd));44$query=mysql_query("insert into tbuser(username,userpwd)values('$name','$pwd')");45$error=mysql_errno();46if($query) {47return"true | add ok";48}else{49return"false |$error";50}51}52catch(Exception$ex) {53return"false |$ex";54}55}56functionDeleteUser($name) {57mysql_connect("localhost", "root", "123");58mysql_select_db("studentdb");59mysql_query("set names gb2312");60$name=trim($name);61$sql0=mysql_query("select userid from tbuser where username='$name'");62$info0=mysql_fetch_array($sql0);63if($info0!=false) {64if(mysql_query("delete from tbuser where username='$name'")) {65return"true | delete ok.(id:" .$info0[0] . ")";66}else{67return"false | 删除失败";68}69}else{70return"false | 删除失败$name不存在";71}72}73functionUpdateUser($id,$name,$pwd) {74if(is_numeric(intval(trim($id)))) {75if($id&&$name&&$pwd) {76mysql_connect("localhost", "root", "123");77mysql_select_db("studentdb");78mysql_query("set names gb2312");79$pwd=md5(trim($pwd));80$isexists=mysql_query("select * from tbuser where userid='$id'");81if(mysql_fetch_array($isexists)) {82$sql0=mysql_query("update tbuser set username='$name',userpwd='$pwd' where userid=$id");83if($sql0) {84return"ture | update ok";85}else{86return"false | 更新失败";87}88}else{89return"false | usrid=$idnot exists.";90}91}else{92return"false |id=$idname=$nameand pwd=$pwd.At least one of them is null.";93}94}else{95return"false |$idis not type of int.";96}97}98}99?>
View Code
与登录无关,只为了记录一下PHP如何在数据库MYSQL上实现CURD操作.
6 效果图