0

Im trying to write a login script that needs a user to to login before they can access the database and when i write out the code i get the login in screen but the screen gives this error: PHP Fatal error: Call to a member function fetch() on boolean in G:\xampp\htdocs\music\auth.php on line 12

I dont know what to do. Heres my code:

<?php
session_start();
$err = "";
if( !empty($_POST['submit']) )
{
    $name = $_POST['user'];
    $pwd = $_POST['password'];

    $music = new PDO('mysql:host=localhost;dbname=music', 'musicphp', 'password');
    $sql = "SELECT id FROM music WHERE username = '$name' AND pwd='$pwd'";
    $users= $music->query($sql);
    $music = $users->fetch();

    if( empty($users['id']) || $users == NULL )
    {
        $err = "Bad username or password";
    }
    else
    {
        $_SESSION['userid'] = $user['id'];
        header('Location: index.php');
    }
}
echo $err;
?>
<form action = "auth.php" method="post">
    Username: <input type="text" name="user"/>
    Password: <input type="password" name="password"/>
    <input type="submit" name="submit" value="Log in" />
</form>
2
  • 1
    Why use PDO if not interested in prepared statements ??? :) Commented Feb 9, 2016 at 2:48
  • @DevashishJaiswal Why not? PDO is modern, more cross platform, and easy to use. Surely you’re not suggesting mysql functions? Commented Mar 17, 2018 at 11:51

1 Answer 1

4

Please use prepared statement

Remove this part

$sql = "SELECT id FROM music WHERE username = '$name' AND pwd='$pwd'";
$users= $music->query($sql);
$music = $users->fetch();

And Replace it with this

$sql = "SELECT id FROM music WHERE username = :name AND pwd=:pwd";
$statement= $music->prepare($sql);
$statement->execute(array(':name'=> $name,':pwd'=>$pwd));
$music =  $statement->fetch();
Sign up to request clarification or add additional context in comments.

10 Comments

Where would i put that?
It worked but appeartnly im locked out of my database
yea but i dont know wat to do t get back to my database
Are you saying that you have dropped your database? and you cannot use it?
it says my access is denied "Connection for controluser as defined in your configuration failed."
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.