PHP - 验证用户是否存在于DB中并显示结果而不重新加载页面

时间:2011-08-18 16:39:02

标签: php jquery mysql database

我想检查数据库中是否存在用户,如果存在则显示某些错误而不重新加载页面(修改div)。知道这段代码有什么问题吗?或任何其他想法如何做到这一点?谢谢

HTML:
<div style="width:510px; height:500px;">
<div class="message">
<div id="alert"></div>
</div>
<form id="signup_form" method="post" action="register.php">
<label class="label">username</label>
<p><input class="signup_form" type="text" name="username"></p>
<label class="label">parola</label>
<p><input class="signup_form" type="text" name="password"></p>
<label class="label">name</label>
<p><input class="signup_form" type="text" name="name"></p>
<label class="label">telefon</label>
<p><input class="signup_form" type="text" name="phone"></p>
<label class="label">email</label>
<p><input class="signup_form" type="text" name="email"></p>

<p><input class="signup_button"  type="submit" value="inregistrare">
</form>

<div class="clear"></div>
</div>

register.php

<?php
include "base.php"; 
$usertaken = '<li class="error">username used</li><br />';
$alert = '';
$pass = 0;
if(!empty($_POST['username']) && !empty($_POST['password']))
{
$username = mysql_real_escape_string($_POST['username']);
$password = md5(mysql_real_escape_string($_POST['password']));
$name = mysql_real_escape_string($_POST['username']);
$phone = mysql_real_escape_string($_POST['phone']);
$email = mysql_real_escape_string($_POST['email']);


 $checkusername = mysql_query("SELECT * FROM details WHERE user = '".$username."'");

 if(mysql_num_rows($checkusername) == 1)
 {
    $pass = 1;
    $alert .="<li>" . $usertaken . "</li>";
 }
 else
 {
    $registerquery = mysql_query("INSERT INTO details (user, pass, name, phone, email) VALUES('".$username."', '".$password."','".$name."','".$phone."', '".$email."')");
    if($registerquery)
    {
        echo "<h1>Success</h1>";
        echo "<p>Your account was successfully created. Please <a href=\"index.php\">click here to login</a>.</p>";
    }
    else
    {
        echo "<h1>Error</h1>";
        echo "<p>Sorry, your registration failed. Please go back and try again.</p>";    
    }       
 }
 if($pass == 1) {
    echo '<script>$(".message").hide("").show(""); </script>';
    echo "<ul>";
    echo $alert;
    echo "</ul>";
 }
}
        ?>

解决方案(将其添加到头部并隐藏.message div)

<script type="text/javascript" src="jquery-latest.pack.js"></script>
<script type="text/javascript" src="jquery.form.js"></script>
<script type="text/javascript">
$(document).ready(function() { 
var options = { 
target:        '#alert',
beforeSubmit:  showRequest,
success:       showResponse
}; 
$('#signup_form').ajaxForm(options); 
}); 
function showRequest(formData, jqForm, options) { 
var queryString = $.param(formData); 
return true; 
} 
function showResponse(responseText, statusText)  {  
} 
$.fn.clearForm = function() {
  return this.each(function() {
var type = this.type, tag = this.tagName.toLowerCase();
if (tag == 'form')
  return $(':input',this).clearForm();
if (type == 'text' || type == 'password' || tag == 'textarea')
  this.value = '';
else if (type == 'checkbox' || type == 'radio')
  this.checked = false;
else if (tag == 'select')
  this.selectedIndex = -1;
  });
};
</script>

3 个答案:

答案 0 :(得分:5)

您需要使用AJAX进行动态页面更新。

看看这里:http://api.jquery.com/jQuery.ajax/了解如何使用jQuery。

您当前的代码使用表单提交,该表单始终会重新加载页面。

答案 1 :(得分:1)

您需要使用ajax。把这样的东西写成JavaScript:

 var xmlHttp;
 function checkUser(user) {
   xmlHttp=GetXmlHttpObject();
   if (xmlHttp==null) {
     alert ("Browser does not support HTTP Request.");
     return;
   }
   var url = "check.php"; //This is where your dynamic PHP file goes
   url = url + "?u=" + user;
   url = url + "&sid=" + Math.random();
   xmlHttp.onreadystatechange = getData;
   xmlHttp.open("GET",url,true);
   xmlHttp.send(null);
 }
 function getData () {
   if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete") {
     if (xmlHttp.responseText == 1) {
           alert('Username free'); //action if username free
         } else {
           alert('This username is taken'); //action if its not
         }
   }
 }
   function GetXmlHttpObject() {
   var xmlHttp=null;
   try {
    // Firefox, Opera 8.0+, Safari
    xmlHttp=new XMLHttpRequest();
   } catch (e) {
     //Internet Explorer
     try {
       xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
     } catch (e) {
       xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
     }
   }
   return xmlHttp;
 }

在check.php文件中,如果用户名是否被使用,只需检查您的数据库,如果没有,只需echo('1')如果是免费的话,请检查echo('0') o,无论你想要什么。该单个号码将作为xmlHttp.responseText处理。你也可以做一些花哨而不是警报的事情,比如图像。你也需要在用户输入时或者提交表单时运行check()fumction,并将用户名表单字段作为参数。希望这会有所帮助。

编辑:哦,我忘了在check.php文件中,$_GET['u']变量包含输入的用户名。检查数据库。

答案 2 :(得分:-1)

如果这一切都在一个页面中,你必须像这样构建它:

<?php

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
   ... do form retrieval/database stuff here ...
   if (error) {
      $message = 'Something dun gone boom';
   }
}

if ($message != '') {
   echo $message;
}
?>

form stuff goes here