I have a class called dbConnect
his function is to connect to the database and manage the data like ( insert, read...etc ) for now, I only made one method getRows
this method suppose to fetchAll
rows from the table, the problem is when I create a new object (new Connection) and call getRows
method nothing happens at all, not even an exception, so what did I do wrong? what I'm missing here?
Core.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;
}
}
}
?>
functions.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>
You never set $this->connected
to true
, so condition if($this->connected === true){
in function getRows()
is never satisfied, ie you won't get your rows, you get false
returned.
Suggest you set $this->connected
to true
when you receive a valid PDO object on connection in your __construct()
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.