[英]Fatal error: Call to a member function bindValue() on a non-object in
I got the error showing above. 我收到上面显示的错误。 I have looked on this website, but I can't find the right fix to solve my problem.
我已经看过这个网站,但是找不到解决我问题的正确方法。
I am trying to write a User- class . 我试图写一个User- class 。 The following code is my code so far.
到目前为止,以下代码是我的代码。
class User
{
private $_id;
public function __construct($id)
{
$this->_id = $id;
}
public function getUsername()
{
global $db;
$query = $db->prepare("SELECT * FROM users WHERE id = ?");
$query->bindValue(1, $this->_id);
$query->execute();
}
}
The result is the following error and I don't know how to fix this... 结果是出现以下错误,我不知道该如何解决...
Fatal error: Call to a member function bindValue() on a non-object in 致命错误:在非对象中调用成员函数bindValue()
Edit: 编辑:
Here is how I am using it: 这是我的使用方式:
$user = new User($_SESSION['logged_in']);
$username = $user->getUsername();
Sidenote: session_start();
旁注:
session_start();
is loaded. 已加载。
Using global variable is really a poor approach. 使用全局变量确实是一种糟糕的方法。
Read this blog entry: 阅读此博客文章:
Global Variables Are Bad 全局变量不好
It explains why it is not a good idea. 它解释了为什么它不是一个好主意。
If the $db
is null, most likely prepare will not return the statement object. 如果
$db
为null,则很可能prepare将不会返回语句对象。
Then $query
will not be a statemnt, therefore bindValue
wont be recognize. 然后
$query
将不是一个statemnt,因此bindValue
不会被识别。
Instead pass the connection to your class, and just stop using globals. 而是将连接传递给您的班级,然后停止使用全局变量。
And also your function was not returning any data, I modify it to return the username. 而且您的函数没有返回任何数据,我对其进行了修改以返回用户名。
class User
{
private $_id;
private $db;
public function __construct($id, $conn)
{
$this->_id = $id;
$this->$db = $conn;
}
public function getUsername()
{
$query = $this->db->prepare("SELECT username FROM users WHERE id = ?");
$query->bindValue(1, $this->_id);
$query->execute();
$data = $query->fetch();
return $data['username'];
}
}
Usage: 用法:
session_start();
$id = $_SESSION['logged_in'];
$conn = new PDO('xxx');
$user = new User($id, $conn);
$username = $user->getUsername();
It seams to me that your query object is $db
not $query
... if so, then it's normal that the $query is missing bindValue()
, because it's not an object, therefor it does not have any methods. 在我看来,您的查询对象是
$db
而不是$query
...如果是这样,则$ query缺少bindValue()
是正常的,因为它不是对象,因此它没有任何方法。
try to use $db->bindValue()
and let us know how it went :D 尝试使用
$db->bindValue()
,让我们知道它如何进行:D
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.