dousong2023 2017-04-06 19:26
浏览 164
已采纳

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

I am trying to figure out why my check database for same username is not running because the code is right but its just not running properly reason why I know the code is right for the query because my email one is working so I think the problem is how I put the query on the page but I am moving it all over the place to see if it works and it just seems to not.

<?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" . "
";
$header .= "Content-type:text/html;charset=iso-8859-1" . "
";
$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条回答 默认 最新

  • duancong6937 2017-04-06 19:50
    关注

    Your sql statement for selecting the user is the same as the one for email (the condition is based on email column). It seems like a copy-paste error...

    Not commenting on the rest of the code (as there is quite a lot to check) I would suggest to strongly consider creating a new function as soon as there is a temptation to copy-paste. Event if it requires some additional work and creativity to write a modular function, there are benefits too. It is less error prone (usually fewer lines of code mean smaller chance of a mistake). The readability improves (if you comment your code with proper explanations).

    EDIT:

    There seems to be a logical error. You use a single variable for indicating $found. If you do not find an email, $found = true. This does not change regardless of finding a duplicate user. Therefore no matter what the user check, if the email is ok, you execute this part of code:

    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");
            }
        }
    
    }
    

    I suggest you use two different variables for email and user ($email_not_found, $user_not_found) and then check for both of them. Or if you find an existing user, you change the $found back to false. Also consider changing the $found to something else as the variable name indicates (at least to me) that the mail/user was found, but is used in the opposite manner ($found = true when user/email do not exist).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 PointNet++的onnx模型只能使用一次
  • ¥20 西南科技大学数字信号处理
  • ¥15 有两个非常“自以为是”烦人的问题急期待大家解决!
  • ¥30 STM32 INMP441无法读取数据
  • ¥15 R语言绘制密度图,一个密度曲线内fill不同颜色如何实现
  • ¥100 求汇川机器人IRCB300控制器和示教器同版本升级固件文件升级包
  • ¥15 用visualstudio2022创建vue项目后无法启动
  • ¥15 x趋于0时tanx-sinx极限可以拆开算吗
  • ¥500 把面具戴到人脸上,请大家贡献智慧,别用大模型回答,大模型的答案没啥用
  • ¥15 任意一个散点图自己下载其js脚本文件并做成独立的案例页面,不要作在线的,要离线状态。