PHP致命错误:在布尔值上调用成员函数fetch()

时间:2016-02-09 02:11:11

标签: php mysql

我试图编写一个登录脚本,需要用户登录才能访问数据库,当我写出代码时,我会在屏幕上登录,但是屏幕会显示以下错误: PHP致命错误:在第12行的G:\ xampp \ htdocs \ music \ auth.php中调用boolean上的成员函数fetch()

我不知道该怎么做。继承我的代码:

<?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>

1 个答案:

答案 0 :(得分:4)

请使用准备好的声明

删除此部分

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

并将其替换为

$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();