[英]calling a class (object ) in PHP OOP
我有一个 class 称为dbConnect
他的fetchAll
是连接到数据库并管理数据,如(插入,读取......等),我只做了一个方法getRows
这个方法假设从表中获取所有行,问题是当我创建一个新的 object (新连接)并调用getRows
方法时,什么都没有发生,甚至没有异常,那么我做错了什么? 我在这里缺少什么?
核心.php
<?php
class dbConnect {
// properties
// Host name
public $db_host = '';
// database username
protected $db_user = '';
// database password
protected $db_pass = '';
// database username
protected $db_name = '';
// connection property @boolean * important
protected $connection;
// connection states property @boolean
public $connected = false;
// Errors handler @boolean property
private $errors = true;
// contstract
public function __construct($db_host, $db_user, $db_pass, $db_name)
{
global $c;
try{
$this->host = $db_host;
$this->username = $db_user;
$this->password = $db_pass;
$this->database = $db_name;
// new PDO instans connection
$this->connection = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->database, $this->username, $this->password);
$this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$this->connection->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
}
catch(PDOException $e){
$this->connected = false;
if($this->errors == true){
return $this->error($e->getMessage());
} else {
return false;
}
}
}
// Destruct destroies all
function __destruct(){
$this->connected = false;
$this->connection = null;
}
// Error Methods Outputs $e //
public function error($errors){
echo $errors;
}
// Fetching Rows Method
public function getRows($query, $params = array()){
if($this->connected === true){
try{
$query = $this->connection->prepare($query);
$query->execute($params);
return $query->fetchAll();
}
catch(PDOException $e){
if($this->errors === true){
return $this->error($e->getMessage());
}else{
return false;
}
}
}else{
return false;
}
}
}
?>
功能。php
<?PHP
include('Core.php');
$db = new dbConnect('127.0.0.1','root','password','project-db'); // i also tried [ localhost ] as hostname //
?>
<HTML>
<head><title></title>
</head>
<body>
<div class="container bg-dark" style="color:whitesmoke; width:auto;">
<?php
$db->getRows('SELECT * FROM `drafts` ORDER BY id DESC');
?>
</div>
</body>
</HTML>
您从未将$this->connected
设置为true
,因此function getRows()
中的条件if($this->connected === true){
永远不会满足,即您不会得到您的行,您会返回false
。
建议您在__construct()
中的 connection 收到有效的 PDO object 时将$this->connected
设置为true
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.