PHP開(kāi)發(fā)留言板教學(xué)之註冊(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"> 用戶名:<input type="text" placeholder="請(qǐng)輸入用戶名" 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)分析一下
連結(jié)資料庫(kù),引入conn.php的檔案
require_once('conn.php');//引入連接資料庫(kù)檔案
我們?cè)趯懺]冊(cè)的時(shí)候,如果資料庫(kù)已存在表單提交的信息,就應(yīng)該不讓其註冊(cè)了,例如:資料庫(kù)中已經(jīng)有了“張三”這個(gè)用戶,註冊(cè)時(shí)再使用“張三”,這樣是不可取的,所以我們首先要獲取表單提交的信息,然後去數(shù)據(jù)庫(kù)查詢,是否存在該信息,代碼如下:
????$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 判斷,若為真即為資料庫(kù)有這些資訊,提示用戶已被註冊(cè)。為假,我們可以註冊(cè),把獲取的資訊加入資料庫(kù)
程式碼如下:
if($res){
?? ??? ?echo "<script>alert('使用者已存在,請(qǐng)重新註冊(cè)');location.href='reg.php';</script>";
?? ?}else{
?? ??? ?$sql1 = "insert into `user` (username,password) values(' $name','$pwd')";
?? ??? ?$result = mysql_query($sql1);
?? ??? ?if($result){##??);
?? ??? ?if($result){##??);
?? ??? ?if($result){##??/clt); .href='message.php';</script>";
?? ??? ?}else{
?? ??? ??? ?echo "<); ;/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('用戶已存在,請(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 完整程式碼如下:###rrreee##########