简体   繁体   English

PHP表单只提交一行数据

[英]PHP form only submits data for one row

I am working on a simple registration system and after hours of research am still stuck.我正在开发一个简单的注册系统,但经过数小时的研究仍然卡住了。

If my database is clear (I delete any rows in the table), and I submit the form, it sends a validation email and activates and allows me to login.如果我的数据库是清晰的(我删除了表中的任何行),并且我提交了表单,它会发送一封验证电子邮件并激活并允许我登录。

If I try to create another account with the same email, I am not getting my error message like I should be, telling the user "the email has already been registered."如果我尝试使用相同的电子邮件创建另一个帐户,我不会收到应有的错误消息,告诉用户“电子邮件已经注册”。 It just takes me to a blank page, even if I use a new email address after the first row has been created.它只是将我带到一个空白页面,即使我在创建第一行后使用新的电子邮件地址。

When I look at my table, the row created by the form (the first time) has the auto-inc ID which is right, the username is input into the row, but password, email, and activation all say '0'.当我查看我的表格时,表单(第一次)创建的行具有正确的 auto-inc ID,用户名输入到行中,但密码、电子邮件和激活都显示为“0”。

Can anyone see where the error is in my code?谁能看到我的代码中的错误在哪里? I need the code to verify that the email entered isn't already used, and if it is, to display the errormessage.我需要代码来验证输入的电子邮件是否已被使用,如果是,则显示错误消息。 If it isn't, it should be creating a new row in the table with the information.如果不是,它应该在包含信息的表中创建一个新行。

I know I need to hash the password.我知道我需要散列密码。 I'm just trying to get the information in the table right before I proceed with security.我只是想在我继续进行安全之前获取表格中的信息。

index.php索引.php

<?php

    include 'sessions.php';

    if(isset($_SESSION['errormessage'])){   
        echo ($_SESSION['errormessage']);
        unset ($_SESSION['errormessage']);
    }
?>

<html>
<head>
  <title>Registration Form</title>
</head>

<body>
  <form name="newForm" method="post" action="createaccount.php">UserName:
    <input type="text" name="newUserName" size="15" maxlength="15">
    <br>Password:
    <input type="password" name="newPass1" size="15">
    <br>Confirm Password:
    <input type="password" name="newPass2" size="15">
    <br>Email:
    <input type="email" name="newEmail" size="15">
    <br>
          <input type="submit" name="newSubmit">
          <input type="reset" name="newReset">
        </p>
  </form>

 <hr>

    <form name="newForm" method="post" action="login.php">
        <strong>Already Registered? Login Here:</strong>
        <br>
    UserName:
    <input type="text" name="UserName" size="15" maxlength="15">
    <br>Password:
    <input type="password" name="Pass1" size="15">
    <br>        
        <input type=submit name=SubmitButton value=Submit>
        <input type=reset name=ResetButton value=Clear>
    </form>     

</body>

</html>

createaccount.php创建帐户.php

<?php

    include ('sessions.php');
    include ('database_connection.php');

//function to test password
function passwordStrength($pwd) {
    //test for at least 8 characters
    if (strlen($pwd) < 8) {
        return false;
    }
    //test for max length
    if (strlen($pwd) > 16) {
        return false;
    } 
    //test to see if password contains number
    if(!preg_match("#[0-9]+#", $pwd)) {
        return false;
    }
    //test to see if password has capital letter
    if(!preg_match("#[A-Z]+#", $pwd)) {
        return false;
    }
    //test to see if password has a lowercase letter
    if(!preg_match("#[a-z]+#", $pwd)) {
        return false;
    }
    //test to see if password has special character
    if(!preg_match("#[^0-9A-Za-z]#", $pwd)) {
        return false;
    }
    //test to see if password contains a space
    if (strpos($pwd, ' ') > 0) {
        return false;
    }
    else {
        return true;
    }

    return true;
}

    if(isset($_POST['newSubmit'])){
            if(empty($_POST['newUserName'])) {
            $_SESSION['errormessage'] = "Please enter a username!";
            header("Location: index.php");
            } 
            else if (strlen($_POST['newUserName']) < 4) {
                $_SESSION['errormessage'] = "Username is too short!";
                header("Location: index.php");
            } else if(strlen($_POST['newUserName']) > 16) {
                $_SESSION['errormessage'] = "Username is too long!";
                header("Location: index.php");
            } else if(empty($_POST['newPass1'])) {
                $_SESSION['errormessage'] = "You must enter a password!";
                header("Location: index.php");
            } else if(empty($_POST['newPass2'])) {
                $_SESSION['errormessage'] = "You must confirm your password!";
                header("Location: index.php");
            } else if($_POST['newPass1'] !== $_POST['newPass2']) {
                $_SESSION['errormessage'] = "Passwords do not match!";
                header("Location: index.php");
            } else if(!passwordStrength($_POST['newPass1'])) {
                $_SESSION['errormessage'] = "Password does not meet requirements!";
                header("Location: index.php");
            } else if(empty($_POST['newEmail'])) {
                $_SESSION['errormessage'] = "Must enter an email address!";
                header("Location: index.php");
            }   else {
                $Email = $_POST['newEmail'];
                $name = $_POST['newUserName'];
                $Password = $_POST['newPass1'];
                //echo "All fields accepted!";
                //$pwd = $_POST['newPass1'];
                //echo hash("sha256", $pwd);
                // Make sure the email address is available:
                $query_verify_email = "SELECT * FROM userDB WHERE email ='$Email'";
                $result_verify_email = mysqli_query($db, $query_verify_email);
                if (!$result_verify_email) {//if the Query Failed ,similar to if($result_verify_email==false)
                    $_SESSION['errormessage'] = "Sorry, that email address has already been registered!<br />If you already have an account, login below.<br /><br />";
                    header("Location: index.php");
                }

                if (mysqli_num_rows($result_verify_email) == 0) { // IF no previous user is using this email .


                    // Create a unique  activation code:
                    $activation = md5(uniqid(rand(), true));


                    $query_insert_user = "INSERT INTO `userDB` ( `username`, `email`, `password`, `activation`) VALUES ( '$name', '$Email', '$Password', '$activation')";


                    $result_insert_user = mysqli_query($db, $query_insert_user);
                if (!$result_insert_user) {
                    echo 'Query Failed ';
                }

                if (mysqli_affected_rows($db) == 1) { //If the Insert Query was successfull.
                    //send the email
                    $to = $_POST['newEmail']; // this is your Email address
                    $from = "mtshort87@gmail.com"; // this is the sender's Email address
                    $subject = "Account Succesfully Created";
                    $message = "Thank you for creating an account. Please activate it now using the link below!";
                    $message2 = "http://cts.gruv.org/short/form/activate.php?username=".$_POST['newUserName']."\n";
                    $headers = "From:" . $from;
                    $headers2 = "From:" . $to;
                    mail($to,$subject,$message2,$message,$headers);
                    mail($from,$subject,$message2,$message,$headers); // sends a copy of the message to the sender
                        $_SESSION['errormessage'] = "A confirmation e-mail has been sent to you. Please activate your account to login.";
                        header("Location: index.php");
                }
                mysqli_close($db);//Close the DB Connection
            }
        }
    }

activate.php激活.php

<?php

include 'sessions.php';
include 'database_connection.php';

if (isset($_GET['Email']) && preg_match('/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/', $_GET['Email']))
{
    $email = $_GET['Email'];
}
if (isset($_GET['key']) && (strlen($_GET['key']) == 32))//The Activation key will always be 32 since it is MD5 Hash
{
    $key = $_GET['key'];
}


if (isset($Email) && isset($key))
{
    // Update the database to set the "activation" field to null

    $query_activate_account = "UPDATE userDB SET activation=NULL WHERE(email ='$Email' AND activation='$key')LIMIT 1";


    $result_activate_account = mysqli_query($db, $query_activate_account) ;

    // Print a customized message:
    if (mysqli_affected_rows($db) == 1)//if update query was successfull
    {
    echo '<div class="success">Your account is now active. You may now <a href="login.php">Log in</a></div>';

    } else
    {
        echo '<div class="errormsgbox">Oops !Your account could not be activated. Please recheck the link or contact the system administrator.</div>';

    }

    mysqli_close($db);

} else {
        echo '<div class="errormsgbox">Error Occured .</div>';
}


?>

If any more information is requested I will edit this post.如果需要更多信息,我将编辑这篇文章。

 $query_verify_email = "SELECT * FROM userDB WHERE email ='$Email'";
 $result_verify_email = mysqli_query($db, $query_verify_email);
 if (!$result_verify_email) {//if the Query Failed ,similar to if($result_verify_email==false)
      $_SESSION['errormessage'] = "Sorry, that email address has already been registered!<br />If you already have an account, login below.<br /><br />";
      header("Location: index.php");
 }

http://php.net/manual/en/mysqli.query.php http://php.net/manual/en/mysqli.query.php

Returns FALSE on failure.失败时返回 FALSE。 For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object .对于成功的 SELECT、SHOW、DESCRIBE 或 EXPLAIN 查询,mysqli_query() 将返回一个 mysqli_result 对象 For other successful queries mysqli_query() will return TRUE.对于其他成功的查询,mysqli_query() 将返回 TRUE。

Since you are using a correct SQL select statement, mysqli_query will return a mysqli_result object.由于您使用了正确的 SQL select 语句, mysqli_query将返回一个mysqli_result对象。

There is a num_rows attribute in mysqli_result that indicates the number of rows found. mysqli_result中有一个num_rows属性,表示找到的行数。 You can use it to check if there is a record with that email.您可以使用它来检查该电子邮件是否有记录。
Always use LIMIT 1 when you expect 1 result.当您期望 1 个结果时,请始终使用LIMIT 1

FIX:使固定:

$query_verify_email = "SELECT * FROM userDB WHERE email ='$Email' LIMIT 1";
$result_verify_email = mysqli_query($mysqli, $query_verify_email);

if (is_object($result_verify_email) && $result_verify_email->num_rows > 0) {
    echo "Email already exists";
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM