Reputation: 17383
I am a beginner in PDO. I am following a tutorial to learning PDO. I want to use a simple select statement to fetch id of users.
but when I run index.php
it dont show any echo
! where is my wrong ?
I have four files :
config => setting username and password...
DB_Connect :
class DB_Connect {
// constructor
function __construct() {
}
// destructor
function __destruct() {
// $this->close();
}
// Connecting to database
public function connect() {
require_once 'include/config.php';
try {
$hostname = DB_HOST ;
$dbname = DB_DATABASE;
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", DB_USER, DB_PASSWORD);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
return $dbh;
}
}
DB_Functions :
class DB_Functions {
private $db;
//put your code here
// constructor
function __construct() {
require_once 'DB_Connect.php';
// connecting to database
$this->db = new DB_Connect();
$this->db->connect();
}
// destructor
function __destruct() {
}
function getUsers(){
$sql = "SELECT * FROM users";
foreach ($this->$db->query($sql) as $row)
{
echo $row->id;
}
/*** close the database connection ***/
// $db = null;
}
}
index.php
<?php
require_once 'include/DB_Functions.php';
$qr = new DB_Functions();
$qr->getUsers();
?>
Upvotes: 0
Views: 194
Reputation:
db_connect
class DB_Connect {
public $dbh;
// constructor
function __construct() {
}
// destructor
function __destruct() {
// $this->close();
}
// Connecting to database
public function connect() {
require_once 'include/config.php';
try {
$hostname = DB_HOST ;
$dbname = DB_DATABASE;
$this->dbh = new PDO("mysql:host=$hostname;dbname=$dbname", DB_USER, DB_PASSWORD);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
}
db_functions
class DB_Functions {
private $db;
//put your code here
// constructor
function __construct() {
require_once 'DB_Connect.php';
// connecting to database
$this->db = new DB_Connect();
$this->db->connect();
}
// destructor
function __destruct() {
}
function getUsers(){
$sql = "SELECT * FROM users";
foreach ($this->db->dbh->query($sql) as $row)
{
echo $row->id;
}
/*** close the database connection ***/
// $db = null;
}
}
You have no database connection because you're now assigning your PDO connection to a variable. So you're connection is not accessible to the rest of your script. At least, that's what I'm thinking at the moment.
Upvotes: 1