简体   繁体   中英

Verifying username/password via MySQL server using PDO functions

I am having some problem connecting properly to the MySQL server using the PDO function. I can't query what I need from the database and I am not quite sure what PDO functions to use. I GET 0 as a result of this. I wish to verify the password and username I enter via the database and make an if statement that launches the session if the information is correct.

Here is my UPDATED code:

<?php
// if a value is given
if (isset($_POST['username' && 'password'));
{

    // starts the session created if login info is correct
    session_start();

    // connectivity to MySQL server
    $db = new PDO('mysql:host=host;dbname=name', 'username', 'password');

    // information entered in form made into a variable
    $username = PDO::quote($_POST['username']); 
    $password = PDO::quote($_POST['password']);

    // after pressing login, checking if the variables exist in the database
    if ($_POST['button'] == 'Login')
    {
        $query = $db->query("SELECT COUNT(*) FROM login WHERE username=:username AND password=:password");
        $query->bindValue(':username', $username, PDO::PARAM_STR);
        $query->bindValue(':password', $password, PDO::PARAM_STR);
        $query->execute();

        // Check the number of rows that match the SELECT statement 
        if($query = $db->fetch(PDO::FETCH_OBJ)) 
        {
            echo "No records found";
        }
        else
        {
            header("Location: members.php");
            $_SESSION['username'] = $_POST['username'];
        }
    }   
    // After pressing register, stores variable and adds it in register field
    else if ($_POST['register'] == 'Register')
    {
        header("Location: register.php");
        $_SESSION['usernamereg'] = $_POST['username'];
    }

    // If no button is pressed, send to index
    else
    {
        header("Location: http://www.gjertgjersund.com");
    }

// closes the if value is given statement
}
?>

<!DOCTYPE html>
<html>
<head>
    <title> Folder </title>
    <link rel="stylesheet" type="text/css" href="frontpage.css">
</head>
<body>

    <div id="box">
    <div id="wrap">


        <center>
        <img src="./img/logo.png" alt="logo">

        <form action='index.php' method='POST' autocomplete='off'>

        <div class="usernameform">
        <input type='text' name='username' style='border: none; font-size: 20px;'>
        </div>

        <br />

        <div class="passwordform">
        <input type='password' name='password' style='border: none; font-size: 20px;'>
        </div>

        <br />

        <div class="registerlogin">
        <input type='submit' name='button' value='Login' class='input'>
        <input type='submit' name='register' value='Register' class='inputtwo'>
        </div>

        </form>
        </center>

    </div>
    </div>

</body>
</html>

That's a very good question, partially because it demonstrates a lot of bad practices that, sadly, exist to this day, almost a decade since this question has been posted. Let's sort them out

Connection

I am having some problem connecting properly to the MySQL server using the PDO function.

That's a fair question and nowhere the connection is just a single line of code. Мany important options have to be set, see a canonical connection example I wrote. You can store the connection code in a separate file and then just include it in your scripts.

Password hashing

You should never store plain passwords in your database. Instead, password must be hashed , using a dedicated function made for the purpose - password_hash() .

Then, to verify the password, you've go to use password_verify()

Don't move any further until you have your passwords properly hashed. Note that the field size for the hashed password must be 60 characters long.

The code to verify username and password

Finally, now we can write the code. It could be much simpler, just a few lines. Actually, only one condition is needed. We shouldn't provide any details as to whether login or username not found - just "Login and password don't match". So here it goes:

<?php
if (isset($_POST['username']))
{
    // get the PDO instance
    include 'pdo.php';

    // getting the record for the given username
    $stmt = $pdo->prepare("SELECT * FROM login WHERE username=?");
    $stmt->execute([$_POST['username']]);
    $user = $stmt->fetch();
    // verifying the password
    if ($user && password_verify($_POST['password'], $user['password']))
    {
        // starts the session created if login info is correct
        session_start();
        $_SESSION['username'] = $user['username'];
        header("Location: members.php");
        exit;
    } else {
        $error = "Login and password don't match";
    }
}

Here, we are checking whether such a user exists and whether the password matches in a single condition.

You should not have to use ' in prepared statement and $username is string not integer

$query = $db->query("SELECT * FROM login WHERE username=:username AND password=:password");
$query->bindValue(':username', $username, PDO::PARAM_STR);
$query->bindValue(':password', $password, PDO::PARAM_STR);
$query->execute();
$row_count = $query->rowCount();
 //{ remove it

Your if condition is wrong change

// if a value is given
if (isset($_POST['username' && 'password'));
{

to

// if a value is given
if (isset($_POST['username']) and isset($_POST['password']))
{

Codepad

Some databases may return the number of rows returned by a SELECT statement. However, this behaviour is not guaranteed for all databases and should not be relied on see Manual . You can use COUNT(*) and fetchColumn() as in following query to emulate rowCount() .

$query = $db->query("SELECT COUNT(*) FROM login WHERE username=:username AND password=:password");
$query->bindValue(':username', $username, PDO::PARAM_STR);
$query->bindValue(':password', $password, PDO::PARAM_STR);
$query->execute();
    // Check the number of rows that match the SELECT statement 
    if($query->fetchColumn() == 0) {
        echo "No records found";
     }else{
            //CODE FOR Success 
            //Etc
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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