这是我的班级代码
<?php
class DatabaseFunctions{
public $serverName = SERVER_NAME ;
public $userName = USER_NAME ;
public $password = PASSWORD ;
public $dbName = DB_NAME ;
public $pdo;
public $error;
public function __construct()
{
$this->db_connect();
}
private function db_connect()
{
try {
$pdo = new PDO("mysql:host=$this->serverName;dbname=$this->dbName",
$this->userName, $this->password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//echo 'Connected successfully';
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
}
public function userIndex($query)
{
//$stmt = $this->pdo->query($query);
$stmt = $this->pdo->prepare($query);
$stmt->execute();
if($stmt-> rowCount() > 0)
{
return $read;
}
else
{
return false;
}
}
}
**这是我的**
<?php
session_start();
include('../../class/config.php');
include('../../class/DatabaseFunctions.php');
if(isset($_SESSION['user'])) {
$db=new DatabaseFunctions();
$query='SELECT * FROM members';
$read=$db->userIndex($query);
print_r($read);
?>
致命错误:未捕获错误:在null上调用成员函数query() 在 D:\ Laravel \ Xamp_new \ htdocs \ mou \ bikroy \ bikroyplus \ class \ DatabaseFunctions.php:33 堆栈跟踪:#0 D:\ Laravel \ Xamp_new \ htdocs \ mou \ bikroy \ bikroyplus \ admin \ pages \ users.php(12): DatabaseFunctions-> userIndex('SELECT * FROM m ...')#1 {main}被抛出 D:\ Laravel \ Xamp_new \ htdocs \ mou \ bikroy \ bikroyplus \ class \ DatabaseFunctions.php 在第33行
是错误..请帮助我.. 注意:数据库已成功连接。但没有pdo函数有效。它说调用成员函数。请帮我。
答案 0 :(得分:2)
在connect函数中,$pdo
仅在函数内部定义,您需要将其分配给$this->pdo
...
function db_connect() {
try {
$this->pdo = new PDO("mysql:host=$this->serverName;dbname=$this->dbName",
$this->userName, $this->password);
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//echo 'Connected successfully';
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
}