检查数据库中的用户名是否有重复项

时间:2017-04-06 19:26:15

标签: php mysql

我试图找出为什么我的检查数据库没有运行相同的用户名,因为代码是正确的,但它只是没有正确运行的原因我知道代码是正确的查询,因为我的电子邮件是工作所以我认为问题是我如何将查询放在页面上,但我将它移动到整个地方以查看它是否有效而且似乎没有。

<?php
//Declare Feedback Error Messages for Each Field on Member Registration Form
  $userErr = "";
  $emailErr = "";
  $passErr = "";
  $capErr = "";
//Get Post Values from form
  $user = $_POST['username'];
  $pass = $_POST['password'];
  $em = $_POST['email'];
  $confirm_code= getCode(5);
  $status = 0;
//Encode value for email and Code.
  $email_encoded = rtrim(strtr(base64_encode($em), '+/', '-_'), '=');
  $code_encoded = rtrim(strtr(base64_encode($confirm_code), '+/', '-_'), '=');
  //$code_decoded = base64_decode(strtr($codenum, '-_', '+/'));



  include_once 'securimage/securimage.php';
  $cVal = new Securimage();
  //validate data
    validate($user, $pass, $em, $cVal);
  if ($userErr != "" || $emailErr!= "" || $passErr!= "" || $capErr!="") {
  Header("Location:../presentation/memberRegistration.php?userMsg=$userErr&passMsg=$passErr&emailMsg=$emailErr&capMsg=$capErr");
}else {
      sanitize($user);
        sanitize($pass);
      sanitize($em);
      $encodedpass= md5($pass);
      //include connection string
  include("../data/dbConnection.php");
    $found = false;
    if ($stmt = mysqli_prepare($mysqli, "SELECT * FROM tblMember WHERE email=?"))
            {
                //bind parameters for markers
                mysqli_stmt_bind_param($stmt, "s", $em);
                //execute query
                mysqli_stmt_execute($stmt);
                //store result
                mysqli_stmt_store_result($stmt);
                //get the number of rows returned
                $test = mysqli_stmt_num_rows($stmt);
                //if no results found
                if($test !=0)
                {
                    $emailErr = "Email Address Already Exists";
                    Header("Location:../presentation/memberRegistration.php?emailMsg=$emailErr");
                }
                else
                {
                    $found = true;
                }
                //close statement
                mysqli_stmt_close($stmt);
            }
            //close connection
                    mysqli_close($mysqli);
          if ($found == true) {
          include("../data/dbConnection.php");
          if ($stmt = mysqli_prepare($mysqli, "SELECT * FROM tblMember WHERE username=?"))
            {
              //bind parameters for markers
              mysqli_stmt_bind_param($stmt, "s", $user);
              //execute query
              mysqli_stmt_execute($stmt);
              //store result
              mysqli_stmt_store_result($stmt);
              //get the number of rows returned
              $test1 = mysqli_stmt_num_rows($stmt);
              //if no results found
              if($test1 !=0)
              {
                $userErr = "Username already Exists";
                Header("Location:../presentation/memberRegistration.php?userMsg=$userErr");
              }
              else
              {
                $found = true;
              }
              //close statement
              mysqli_stmt_close($stmt);
            }
            //close connection
                mysqli_close($mysqli);
          }

if ($found == true) {
        include("../data/dbConnection.php");
    if ($stmt = mysqli_prepare($mysqli, "INSERT INTO tblMember(username, password, email, code, status) VALUES (?, ?, ?, ?, ?)"))
    {//bind parameters to the statement object

        mysqli_stmt_bind_param($stmt, "ssssi", $user, $encodedpass, $em,  $confirm_code, $status);
        $feedback = "";
        if(mysqli_stmt_execute($stmt)){
      //Call to Send Email.
            sendEmail($em, $confirm_code, $email_encoded);
            $feedback = "Your Registration has been successful and <p>Your Confirmation link Has Been Sent To Your Email Address..";
            Header("Location:sendEmail.php?feedbackMsg=$feedback&confirmCode=$code_encoded&em=$email_encoded");
        }else{
            $feedback.= "Your Registration has been unsuccessful.";
            Header("Location:../presentation/memberRegistration.php?feedbackMsg=$feedback");
        }
    }

}

}

//Email
function sendEmail($email, $code, $encodeEmail){


$to=$email;


$subject="Activation Link For Your Account";


$header = "MIME-Version: 1.0" . "\r\n";
$header .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$header .="From:WAD<sheena.s.sylvester@gmail.com>";


$message = "
<html>
<head>
<title>HTML email</title>
</head>
<body style='background-color:red'>
 <h2 bgcolor='#0099ff'><i>Your Activation Link</i></h2>
 <p>Hey Here is your Activation Code:$code

 <br/>Please click on the link below to activate your account status</p>
 <a href='http://localhost/royalGreenwhich/php/logic/sendEmail.php?confirmCode=$code&em=$encodeEmail'>Click Here</a> To activate your account.
</body>
</html>";

// send email using PHP mail function
ini_set("smtp_port","25");
$sentmail = mail($to,$subject,$message,$header);

// if your email succesfully sent
if($sentmail){
 echo "<p>Your Confirmation link Has Been Sent To Your Email Address.";
}
else {
 echo "Cannot send Confirmation link to your e-mail address";
}

}


function getCode($len){
      $result = "";
      $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
      $charArray = str_split($chars);
      for($i = 0; $i < $len; $i++){
        $randItem = array_rand($charArray);
        $result .= "".$charArray[$randItem];
      }
      return $result;
  }
//Function to SANITIZE (Clean) datax`
function sanitize($data){
  $data = trim($data);
  $data = stripslashes($data);
  $data = filter_var($data, FILTER_SANITIZE_SPECIAL_CHARS);
  $data = filter_var($data, FILTER_SANITIZE_STRING);
  $data = filter_var($data, FILTER_SANITIZE_STRING);
  $data = filter_var($data, FILTER_SANITIZE_STRING);

  //for,at data for storage (maintain uniformity)
  $data = strtolower($data);
  $data = ucfirst($data);

  return $data;
}//end sanitize function

  function validate($userVal, $passVal, $emVal, $cVal){
        global $userErr;
        global $passErr;
        global $emailErr;
        global $capErr;
        $valid = true;

    if($userVal == null || $userVal == ""){
      $userErr = "Username Field  required.";
            $valid = false;
    }

    if($passVal == null || $passVal == ""){
      $passErr = "Password Field  required.";
            $valid = false;
    }

    if($emVal == null || $emVal == ""){
      $emailErr = "Email Field required.";
            $valid = false;
    }

    if ($cVal->check($_POST['captcha_code']) == false){
            $capErr .= "Please try again. <br/>You have inserted the wrong Captcha";
            $valid = false;
        }

return true;
}
 ?>

2 个答案:

答案 0 :(得分:0)

两个数据库检查查询都在执行相同的检查WHERE email=?。如果要检查用户名的唯一性,则需要将第二个查询更改为

        if ($stmt = mysqli_prepare($mysqli, "SELECT * FROM tblMember WHERE username=?"))

另一种方法是使用DBMS的唯一字段属性:SQL UNIQUE。使用提供的用户名和电子邮件尝试插入并处理返回的错误,并在需要时将其报告给用户。

答案 1 :(得分:0)

用于选择用户的sql语句与用于电子邮件的语句相同(条件基于email列)。这似乎是一个复制粘贴错误...

没有评论其余的代码(因为有很多要检查的内容)我建议一旦有复制粘贴的诱惑就强烈考虑创建一个新函数。事件如果需要一些额外的工作和创造力来编写模块化功能,也有好处。它不易出错(通常代码行数越少意味着错误的可能性越小)。可读性得到改善(如果您使用正确的解释对代码进行评论)。

编辑:

似乎存在逻辑错误。您使用单个变量来指示$found。如果您没有找到电子邮件,请$found = true。无论是否找到重复的用户,这都不会改变。因此,无论用户检查什么,如果电子邮件都没问题,您执行这部分代码:

if ($found == true) {
        include("../data/dbConnection.php");
    if ($stmt = mysqli_prepare($mysqli, "INSERT INTO tblMember(username, password, email, code, status) VALUES (?, ?, ?, ?, ?)"))
    {//bind parameters to the statement object

        mysqli_stmt_bind_param($stmt, "ssssi", $user, $encodedpass, $em,  $confirm_code, $status);
        $feedback = "";
        if(mysqli_stmt_execute($stmt)){
      //Call to Send Email.
            sendEmail($em, $confirm_code, $email_encoded);
            $feedback = "Your Registration has been successful and <p>Your Confirmation link Has Been Sent To Your Email Address..";
            Header("Location:sendEmail.php?feedbackMsg=$feedback&confirmCode=$code_encoded&em=$email_encoded");
        }else{
            $feedback.= "Your Registration has been unsuccessful.";
            Header("Location:../presentation/memberRegistration.php?feedbackMsg=$feedback");
        }
    }

}

我建议您为电子邮件和用户使用两个不同的变量($ email_not_found,$ user_not_found),然后检查它们。或者,如果找到现有用户,则将$ found更改为false。还要考虑将$ found更改为其他内容,因为变量名称指示(至少对我来说)找到了邮件/用户,但是以相反的方式使用($found = true当用户/电子邮件不存在时)。