我为我的DB-Connection设置了以下代码,但是我无法从另一个.php文件(在另一个目录中)创建到我的数据库的连接:
我的database.php文件:
<?php
ini_set('display_errors', 'On');
public class Database {
public function __construct() {
$this->dsn = 'mysql:host=xxx;dbname=xxx';
$this->username = 'xxx';
$this->password = 'xxx';
}
public function __construct($dsn, $username, $password) {
$this->dsn = $dsn;
$this->username = $username;
$this->password = $password;
}
public function db_connect() {
try {
$database = new PDO($this->dsn , $this->username, $this->password);
return $database;
} catch(PDOException $e) {
echo $e->getMessage();
}
}
public function run_query($database, $query){
try {
$result = $database->prepare($query);
$result->execute();
return $result;
} catch (Exception $e) {
echo $e->getMessage();
die();
}
}
}
?>
此文件的目录是 currentdirectory /php/database.php。
我正尝试使用以下代码在另一个文件(名为page.php)中实例化数据库连接:
include("php/database.php")
$database = new Database();
$connection = $database->db_connect();
$result = $database->run_query($connection, $query);
此文件的目录是 currentdirectory /page.php。
我一直在寻找一个错误,但是看不出我做错了什么。关于PDO-DB类的其他问题也没有给我带来更多帮助。在此先感谢您的帮助!
答案 0 :(得分:3)
public
,private
,protected
用于Class方法和/或属性,不适用于类本身。
您不应该有2个构造函数,或者两个具有相同名称的函数,您将收到致命错误,并且无法重新声明...&#39;
请参阅下面的示例 它使用dsn组件的私有属性,pdo对象本身和pdo语句 您可以在方法中返回这些,以便链接它们。
<?php
class Database {
private $host;
private $username;
private $password;
private $database;
private $pdo;
private $stmt;
public function __construct($host,$user,$pass,$db) {
$this->host = $host;
$this->username = $user;
$this->password = $pass;
$this->database = $db;
$dsn = 'mysql:dbname=' . $this->database .';host=' . $this->host;
try {
$this->pdo = new PDO($dsn, $this->username, $this->password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
}
public function query($query){
$this->stmt = $this->pdo->prepare($query);
return $this;
}
public function getResults(){
$this->stmt->execute();
return $this->stmt->fetchAll(PDO::FETCH_ASSOC);
}
}
用法
// include the file
$db = new Database('localhost','root','','db_name');
print_r($db->query('select * from my_table limit 10')->getResults());
答案 1 :(得分:1)
您需要在Content-Type:[multipart/alternative]
文件中进行一些更改,因此您的文件代码应为:
database.php
你<?php
ini_set('display_errors', 'On');
class Database{
public function __construct(){
$this->dsn = 'mysql:host=xxx;dbname=xxx';
$this->username = 'xxx';
$this->password = 'xxx';
}
public function db_connect() {
try {
$database = new PDO($this->dsn , $this->username, $this->password);
return $database;
} catch(PDOException $e) {
echo $e->getMessage();
}
}
public function run_query($database, $query){
try {
$result = $database->prepare($query);
$result->execute();
return $result;
} catch (Exception $e) {
echo $e->getMessage();
die();
}
}
}
?>
文件代码应为:
page.php
include("php/database.php")
$database = new Database();
$connection = $database->db_connect();
$query = "SELECT * FROM table";
$result = $database->run_query($connection, $query);
范围仅适用于变量/函数。这不适用于public
。