Php 使用类内的PDO连接到数据库
我有两个文件file1.php和database.php。我在database.php文件中有一个类“Connection”。我将调用此函数作为向类“bar”传递查询。但我有两个错误:Php 使用类内的PDO连接到数据库,php,mysql,pdo,Php,Mysql,Pdo,我有两个文件file1.php和database.php。我在database.php文件中有一个类“Connection”。我将调用此函数作为向类“bar”传递查询。但我有两个错误: 1.Notice: Undefined variable: conn... on line 22 2.Fatal error: Cannot access empty property in.. on line 22 这些是我正在使用的代码。多谢各位 file1.php require_once('databa
1.Notice: Undefined variable: conn... on line 22
2.Fatal error: Cannot access empty property in.. on line 22
这些是我正在使用的代码。多谢各位
file1.php
require_once('database.php');
$c = new Connection();
$c->bar("Select id, firstname, lastname from users");
$c->execute();
database.php
class Connection{
public $conn;
public function __construct()
{
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "testing_pdo";
try {
$this->conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$this->conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$this->conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
} catch (Exception $e) {
echo 'ERROR: ' . $e->getMessage();
}
}
public function bar($sql)
{
$this->conn->prepare($sql);
return $this->conn->execute();
}
}
我终于成功了。我在两个文件中都做了一些更改
database.php
class Connection{
private $servername = "localhost";
private $username = "root";
private $password = "";
private $dbname = "testing_pdo";
private $conn;
private $error;
private $stmt;
public function __construct()
{
try {
$this->conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$this->conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$this->conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
} catch (Exception $e) {
$this->error = $e->getMessage();
}
}
public function bar($sql)
{
$this->stmt = $this->conn->prepare($sql);
}
public function resultset(){
$this->execute();
return $this->stmt->fetchAll(PDO::FETCH_ASSOC);
}
}
file1.php
include ('database.php');
$c = new Connection();
$c->bar("Select id, firstname, lastname from users");
$c->resultset();
它是
$this->conn
到处都是一个类;在条形函数中,我正在使用$this->$connI重复:它是$this->conn
任何地方都是一个类。我得到了相同的错误强制性链接:@yourcomsense是的,我正在学习PDO。如果你有更好的解决方案,你可以帮助我学习。围绕PDO编写自己的有限代理是什么想法?虽然PDO已经是一个类,由一个显然比你有更多知识的人编写?PDO有什么问题使您无法按原样使用它?