简体   繁体   English

user_login和password_login正确,但是不起作用PDOPHP

[英]user_login and password_login correct, but are not working PDOPHP

I am trying to get my login script to work using PDO. 我正在尝试使我的登录脚本能够使用PDO进行工作。 The problem I am having is that when a user types in his/her username and passsword, it goes to the section of the code where it says it is incorrect, even if the password is correct. 我遇到的问题是,当用户键入他/她的用户名和密码时,即使密码是正确的,它也会转到代码部分,指出它是错误的。 What can I do to fix this, and where can I implement the PDO error to show up to possibly help diagnose the problem. 我该怎么办才能解决此问题,以及在哪里可以实施PDO错误以显示可能有助于诊断问题的方法。

The Login Script from index.php 来自index.php的登录脚本

<?
//Login Script
if (isset($_POST["user_login"]) && isset($_POST["password_login"])) {
    $user_login = preg_replace('#[^A-Za-z0-9]#i', '', $_POST["user_login"]); // filter everything but numbers and letters
    $password_login = preg_replace('#[^A-Za-z0-9]#i', '', $_POST["password_login"]); // filter everything but numbers and letters
    $password_login=md5($password_login);
    $db = new PDO('mysql:host=localhost;dbname=socialnetwork', 'root', 'abc123');
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $sql = "SELECT id FROM users WHERE username = ':user_login' AND password = ':password_login' LIMIT 1";
    $db->prepare($sql);
    if ($db->execute(array(
    ':user_login' => $user_login,
    ':password_login' => $password_login))); {
        if ($sql->rowCount() > 0){
            while($row = $sql->fetch($sql)){
                $id = $row["id"];
            }
            $_SESSION["id"] = $id;
            $_SESSION["user_login"] = $user_login;
            $_SESSION["password_login"] = $password_login;
            exit("<meta http-equiv=\"refresh\" content=\"0\">");
        } else {
            echo 'Either the password or username you have entered is incorrect. Please check them and try again!';
            exit();
        }
    }
}
?>

index.php index.php

<? include("inc/incfiles/header.inc.php"); ?>
<?
$reg = @$_POST['reg'];
//declaring variables to prevent errors
$fn = ""; //First Name
$ln = ""; //Last Name
$un = ""; //Username
$em = ""; //Email
$em2 = ""; //Email 2
$pswd = ""; //Password
$pswd2 = ""; //Password 2
$d = ""; //Sign up Date
$u_check = ""; //Check if username exists
//registration form
$fn = @$_POST['fname'];
$ln = @$_POST['lname'];
$un = @$_POST['username'];
$em = @$_POST['email'];
$em2 = @$_POST['email2'];
$pswd = @$_POST['password'];
$pswd2 = @$_POST['password2'];
$d = date("y-m-d"); // Year - Month - Day

if ($reg) {
    if ($em==$em2) {
        // Check if user already exists
        $statement = $db->prepare('SELECT username FROM users WHERE username = :username');
            if ($statement->execute(array(':username' => $un))) {
                if ($statement->rowCount() > 0){
                    //user exists
                    echo "Username already exists, please choose another user name.";
                    exit();
                }
            }
                    //check all of the fields have been filled in
                        if ($fn&&$ln&&$un&&$em&&$em2&&$pswd&&$pswd2) {
                            //check that passwords match
                                if ($pswd==$pswd2) {
                                    //check the maximum length of username/first name/last name does not exceed 25 characters
                                        if (strlen($un)>25||strlen($fn)>25||strlen($ln)>25) {
                                            echo "The maximum limit for username/first name/last name is 25 characters!";
                                        }
                                        else
                                            {
                                                //check the length of the password is between 5 and 30 characters long
                                                    if (strlen($pswd)>30||strlen($pswd)<5) {
                                                        echo "Your password must be between 5 and 30 characters long!";
                                                    }
                                                    else
                                                        {
                                                            //encrypt password and password 2 using md5 before sending to database
                                                                $pswd = md5($pswd);

                                                                $pswd2 = md5($pswd2);

                                                                $db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
                                                                $sql = 'INSERT INTO users (username, first_name, last_name, email, password, sign_up_date)';
                                                                $sql .= 'VALUES (:username, :first_name, :last_name, :email, :password, :sign_up_date)';

                                                                $query=$db->prepare($sql);

                                                                $query->bindParam(':username', $un, PDO::PARAM_STR);
                                                                $query->bindParam(':first_name', $fn, PDO::PARAM_STR);
                                                                $query->bindParam(':last_name', $ln, PDO::PARAM_STR);
                                                                $query->bindParam(':email', $em, PDO::PARAM_STR);
                                                                $query->bindParam(':password', $pswd, PDO::PARAM_STR);
                                                                $query->bindParam(':sign_up_date', $d, PDO::PARAM_STR);

                                                                $query->execute();

                                                                $query=$db->prepare($sql);

                                                                $array = array(
                                                                ':username' => $un,
                                                                ':first_name' => $fn,
                                                                ':last_name' => $ln,
                                                                ':email' => $em,
                                                                ':password' => $pswd,
                                                                ':sign_up_date' => $d);
                                                                $query->execute($array);

                                                                die("<h2>Welcome to Rebel Connect</h2>Login to your account to get started.");
                                                        }
                                            }
                                }
                                else {
                                    echo "Your passwords do not match!";
                                }
                        }
                else
                    {
                        echo "Please fill in all fields!";
                    }
            }
    else {
        echo "Your e-mails don't match!";
    }
}
?>
<?
//Login Script
if (isset($_POST["user_login"]) && isset($_POST["password_login"])) {
    $user_login = preg_replace('#[^A-Za-z0-9]#i', '', $_POST["user_login"]); // filter everything but numbers and letters
    $password_login = preg_replace('#[^A-Za-z0-9]#i', '', $_POST["password_login"]); // filter everything but numbers and letters
    $password_login=md5($password_login);
    $db = new PDO('mysql:host=localhost;dbname=socialnetwork', 'root', 'abc123');
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $sql = "SELECT id FROM users WHERE username = ':user_login' AND password = ':password_login' LIMIT 1";
    $db->prepare($sql);
    if ($db->execute(array(
    ':user_login' => $user_login,
    ':password_login' => $password_login))); {
        if ($sql->rowCount() > 0){
            while($row = $sql->fetch($sql)){
                $id = $row["id"];
            }
            $_SESSION["id"] = $id;
            $_SESSION["user_login"] = $user_login;
            $_SESSION["password_login"] = $password_login;
            exit("<meta http-equiv=\"refresh\" content=\"0\">");
        } else {
            echo 'Either the password or username you have entered is incorrect. Please check them and try again!';
            exit();
        }
    }
}
?>
<table class="homepageTable">
        <tr>
            <td width="60%" valign="top">
             <h2>Already a member? Login below.</h2>
             <form action="index.php" method="post" name="form1" id="form1">
                <input type="text" size="25" name="user_login" id="user_login" placeholder="username" />
                <br />
                <input type="password" size="25" name="password_login" id="password_login" placeholder="password" />
                <br />
                <input type="submit" name="button" id="button" value="Login to your account!">
             </form>
            </td>
            <td width="40%" valign="top">
             <h2>Sign up below...</h2>
            <form action="#" method="post">
            <input type="text" size="25" name="fname" placeholder="First Name" value="<? echo $fn; ?>">
            <input type="text" size="25" name="lname" placeholder="Last Name" value="<? echo $ln; ?>">
            <input type="text" size="25" name="username" placeholder="Username" value="<? echo $un; ?>">
            <input type="text" size="25" name="email" placeholder="Email" value="<? echo $em; ?>">
            <input type="text" size="25" name="email2" placeholder="Re-enter Email" value="<? echo $em2; ?>">
            <input type="password" size="25" name="password" placeholder="password" value="<? echo $pswd; ?>">
            <input type="password" size="25" name="password2" placeholder="Re-enter Password" value="<? echo $pswd2; ?>"><br />
            <input type="submit" name="reg" value="Sign Up!">
            </form>
            </td>
        </tr>
</table>
</body>
</html>

logout.php logout.php

<?
session_start();
session_destroy();
header("Location: index.php");
?>

home.php home.php

<?
session_start();
$user = $_SESSION["user_login"];
//If the user is not logged in
if (!isset($_SESSION["user_login"])) {
    header("location: index.php");
    exit();
}
else
{
//If the user is logged in
echo "Hi, $user, You're logged in<br />Welcome to what is soon to be your NEWSFEED 
<a href=\"logout.php\">Logout?</a>
";
}
?>

header.inc.php header.inc.php

<?
include ("inc/scripts/db_connect.inc.php");
session_start();
if (!isset($_SESSION["user_login"])) {

}
else
{
header("location: home.php");
}
?>
<html>
<head>
<link href="css/main.css" rel="stylesheet" type="text/css">
<title>Rebel Reach - PHS Student Social Network</title>
</head>
<body>
<div class="headerMenu">
      <div id="wrapper">
            <div class="logo">
                  <img src="img/find_friends_logo.png">
            </div>
            <div class="search_box">
                  <form method="get" action="search.php" id="search">
                  <input name="q" type="text" size="60" placeholder="Search..." />
                  </form>
            </div>
            <div id="menu">
                  <a href="#">Home</a>
                  <a href="#">About</a>
                  <a href="#">Sign Up</a>
                  <a href="#">Login</a>
            </div>
      </div>
</div>
<br />
<br />
<br />
<br />

Not an answer but some advice for your code that couldn't fit in the comment. 不是答案,而是一些不适合注释的代码建议。 You can greatly reduce your code; 您可以大大减少代码; actually you shouldn't repeat functionality too often... You can reduce: 实际上,您不应该过多地重复功能...您可以减少:

$fn = ""; //First Name
$ln = ""; //Last Name
...
$fn = @$_POST['fname'];
$ln = @$_POST['lname'];
...

To half by writting it like this: 像这样写到一半:

$fn = (!empty($_POST['fname'])) ? $_POST['fname'] : '';
$ln = (!empty($_POST['lname'])) ? $_POST['lname'] : '';
$un = (!empty($_POST['username'])) ? $_POST['username'] : '';
$em = (!empty($_POST['email'])) ? $_POST['email'] : '';
$em2 = (!empty($_POST['email2'])) ? $_POST['email2'] : '';
$pswd = (!empty($_POST['password'])) ? $_POST['password'] : '';
$pswd2 = (!empty($_POST['password2'])) ? $_POST['password2'] : '';

Furthermore, although this would require some other changes, you can reduce that to a couple of lines by writing it in an array like this: 此外,尽管这需要进行其他一些更改,但是您可以通过将其写入如下数组来将其减少到几行:

// Retrieve user data
foreach (array('fname', 'lname', 'username', 'email', 'email2', 'password', 'password2') as $Value)
  $User[$Value] = (!empty($_POST[$Value])) ? $_POST[$Value] : '';

I think your problem is here: 我认为您的问题在这里:

"SELECT id FROM users WHERE username = ':user_login' AND password = ':password_login' LIMIT 1";

When you use PDO prepare method like ? 当使用PDO时,准备方法如? or : do not use single quotation mark ('). 或:请勿使用单引号(')。

correct it like this: 像这样更正它:

"SELECT id FROM users WHERE username = :user_login AND password = :password_login LIMIT 1";

I hope now it will work! 我希望现在能正常工作!

RE your "Fatal error: call to undefined method PDO::execute() in ... line 110" issue: RE您的“致命错误:在第110行中调用未定义的方法PDO :: execute()”问题:

"execute()" is a method in PDOStatement, not PDO, which is why your "$db->execute..." blew up. “ execute()”是PDOStatement中的方法,而不是PDO中的方法,这就是为什么您的“ $ db-> execute ...”被炸毁的原因。

(I know this should be a comment, but I'm not allowed yet. Sorry) (我知道这应该是评论,但目前还不允许。抱歉)

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

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