Reputation: 157
I'm sure this has been asked a few times, but I can't seem to find a straight forward or well explained answer. I'm attempting to create a Account Object/Class within PHP, where I can retrieve data from an account. The issue I'm having is that I cannot include my database.php class so I can retrieve all the created accounts.
I'm fairly new with PHP and don't have an expansive knowledge on how a lot of the processes or conventions work. The error/warning I'm running into is this;
Warning: include(../database.php): failed to open stream: No such file or directory in ~/account.php on line 3
Here is my account.php class
<?php
include '../database.php';
class Account {
protected $username, $email;
protected function getEmail() {
return $this->email;
}
protected function getUsername() {
return $this->username;
}
public function __construct($username, $email) {
$this->username = $username;
$this->email = $email;
}
public static function getUser($username) {
$statement = getConnection()->prepare('SELECT * FROM account WHERE username=?');
$statement->bindValue(1, $username);
if ($rows = $statement->fetch()) {
$account = new Account($rows['username'], $rows['email']);
}
return $account;
}
}
Here is my database.php incase I've done something wrong or may need to change things
<?php
function getConnection() {
$dbh = new PDO("mysql:host=127.0.0.1;dbname=mcsl;port3306", "root", "");
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
return $dbh;
}
Directory Structure:
Upvotes: 0
Views: 3256
Reputation: 9581
You can use include (dirname(__FILE__)."/../database.php")
to access the database.php file in the account.php file
Upvotes: 3
Reputation: 146450
You currently have a mix of object-oriented and procedural code.
Adding database features to a class is normally accomplished by dependency injection. In other words, you pass the database object as argument to whatever method needs it and use type hinting to enforce it, e.g.:
public static function getUser(MyConnectionClassOrInterface $db, $username) {
}
As about your include, you're using relative paths, which are relative to main script, not current file. You can build absolute paths or use a more elaborate class auto-loader.
Upvotes: 0