PHP開(kāi)發(fā)留言板教程之注冊(cè)功能
看下面的一段代碼
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>注冊(cè)</title> <style type="text/css"> *{margin: 0px;padding: 0px;} body{ background:#eee;} #div{width:300px;height:400px; background:#B1FEF9;margin:0 auto;margin-top:150px; border-radius:20px;} h3{margin-left:48px;padding-top:60px;} h4{margin-left:120px;padding-top:60px;font-size: 18px;} #cnt{width:280px;height:370px;margin-left:33px;padding-top:60px;} .sub1{ width:70px;height:30px;border:1px solid #fff; background:#eee;margin-left:150px;margin-top:20px;} </style> </head> <body> <div id="div"> <h4>會(huì)員注冊(cè)</h4> <div id="cnt"> <form method="post" action="regin.php"> 用戶(hù)名:<input type="text" placeholder="請(qǐng)輸入用戶(hù)名" name="username"> <br><br> 密 碼:<input type="password" placeholder="請(qǐng)輸入密碼" name="password"> <br><br> <input type="submit" value="注冊(cè)" class="sub1"> </form> </div> </div> </body> </html>
注冊(cè)頁(yè)面是提交到regin.php ,下面我們來(lái)分析一下
鏈接數(shù)據(jù)庫(kù),引入conn.php的文件
require_once('conn.php');//引入連接數(shù)據(jù)庫(kù)文件
我們?cè)趯?xiě)注冊(cè)的時(shí)候,如果數(shù)據(jù)庫(kù)已存在表單提交的信息,就應(yīng)該不讓其注冊(cè)了,例如:數(shù)據(jù)庫(kù)中已經(jīng)有了“張三”這個(gè)用戶(hù),注冊(cè)時(shí)再使用“張三”,這樣是不可取的,所以我們首先要獲取表單提交的信息,然后去數(shù)據(jù)庫(kù)查詢(xún),是否存在該信息,代碼如下:
????$name = $_POST['username'];
?? ?$pwd? = md5($_POST['password']);
?? ?$sql = "select * from user where username='$name'";
?? ?$info = mysql_query($sql);
?? ?$res = mysql_num_rows($info);
然后我們要對(duì) $res 進(jìn)行判斷,如果為真即為數(shù)據(jù)庫(kù)存在該信息,提示用戶(hù)已被注冊(cè)。為假,我們可以注冊(cè),把獲取的信息添加到數(shù)據(jù)庫(kù)
代碼如下:
if($res){
?? ??? ?echo "<script>alert('用戶(hù)已存在,請(qǐng)重新注冊(cè)');location.href='reg.php';</script>";
?? ?}else{
?? ??? ?$sql1 = "insert into `user` (username,password) values('$name','$pwd')";
?? ??? ?$result = mysql_query($sql1);
?? ??? ?if($result){
?? ??? ??? ?echo "<script>alert('注冊(cè)成功');location.href='message.php';</script>";
?? ??? ?}else{
?? ??? ??? ?echo "<script>alert('注冊(cè)失敗');location.href='reg.php';</script>";
?? ??? ?}
?? ?}
reg.php 完整代碼如下:
<?php require_once('conn.php');//引入連接數(shù)據(jù)庫(kù)文件 //注冊(cè) $name = $_POST['username']; $pwd = md5($_POST['password']); $sql = "select * from user where username='$name'"; $info = mysql_query($sql); $res = mysql_num_rows($info); if($res){ echo "<script>alert('用戶(hù)已存在,請(qǐng)重新注冊(cè)');location.href='reg.php';</script>"; }else{ $sql1 = "insert into `user` (username,password) values('$name','$pwd')"; $result = mysql_query($sql1); if($result){ echo "<script>alert('注冊(cè)成功');location.href='message.php';</script>"; }else{ echo "<script>alert('注冊(cè)失敗');location.href='reg.php';</script>"; } } ?>