PHP致命错误:在布尔值上调用成员函数fetch()
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>
我试图编写一个登录脚本,需要用户登录才能访问数据库和我写的时候 我在屏幕上输入了代码,但是屏幕出现了这个错误:
PHP致命错误:在G:\ xampp \ htdocs \ music \ auth.php上调用布尔中的成员函数fetch() 12 strong> p>
我不知道该怎么做。 继承我的代码: p>
&lt;?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-&gt; query($ sql );
$ music = $ users-&gt; fetch();
if(empty($ users ['id'])|| $ users == NULL)
{
$ err =“Bad 用户名或密码“;
}
其他
{
$ _SESSION ['userid'] = $ user ['id'];
header('Location:index.php');
}
}
echo $ err;
?&gt;
&lt; form action =“auth.php”method =“post”&gt;
用户名:&lt; input type =“text”name =“user”/&gt; \ n密码:&lt; input type =“password”name =“password”/&gt;
&lt; input type =“submit”name =“submit”value =“登录”/&gt;
&lt; / form&gt; \ n code> pre>
div>
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();