Code
connect.php
$username = "USERNAME";
$password = "PASSWORD";
$hostname = "HOSTNAME";
$dbname = 'DATABASE';
try { $dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password); }
catch(PDOException $e){ echo($e->getMessage()); }
users.php
include "/connect.php";
class User
{
private $id, $name1, $name2, $email, $pic, $league_id;
//Constructor
public function __construct($id)
{
$stmt = $dbh->prepare("SELECT * FROM `users` WHERE `id`=?");
$stmt->execute(array($id));
if($stmt->rowCount()<1) exit("Could not find user");
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$this->id = $row["id"];
$this->name1 = $row["name1"];
$this->name2 = $row["name2"];
$this->pic = $row["pic"];
$this->league_id = $row["league_id"];
}
//functions - Get
public function getId() { return $this->id; }
public function getName1(){ return $this->name1; }
public function getName2(){ return $this->name2; }
public function getFullName() { return $this->name1 . " " . $this->name2; }
public function getPic(){ return $this->pic; }
public function getLeagueId(){ return $this->league_id; }
}
index.php
if(isLoggedIn()) {
$user = new User($_SESSION["userid"]);
echo "Welcome back, ".$user->getFullName()."!";
}
Issue
I'm new to classes and OOP in PHP so apologies for the code.
I connect to the database in connect.php
, however I'm having difficulty processing queries in the __constructor
function.
I understand that I cannot include
the connection in the constructor. I also see that the code works if I directly insert the code from connect.php
into the function.
However, I don't want to have to connect to the database each time I want to make a query; is there a method for me to connect outside of the __construct
function?
As far as being a duplicate, the linked question does not answer this one. My question is: "How can I access the object in /connect.php
in the __construct
function of my object?"