I am trying to pass values gathered from PDO in the Datamanager object to the User object.
- The user object is initally called with a request to retrieve user with ID.
- The user creates a connection to the datamanager in the construct.
- The datamanager construct calls the PDO connection.
- Running the user select creates the query to preform on the database.
- The query is then passed to the datamanager which handles the query and returning the results.
- This results should be passed / set to the user object.
I’m not sure if it is step 5 or 6 that is wrong.
class Datamanager {
public function __construct() {
try {
$this->dbh = new PDO("mysql:host=$this->hostName;dbname=$this->dbName", $this->dbUser, $this->dbPassword);
} catch(PDOException $e) {
echo $e->getMessage();
}
}
public function runQuery($query, $obj){
try {
$STH = $this->dbh->query($query);
$STH->setFetchMode(PDO::FETCH_INTO, $obj);
} catch(PDOException $e) {
echo $e->getMessage();
}
return($obj);
}
class User {
public $user_id;
public $user_name;
public $user_password;
public $session_id;
private $dbc;
public function __construct() {
$this->dbc = new Datamanager();
}
function selectUser ($userID, $obj) {
$query = 'SELECT user_id, user_name, user_password, session_id FROM users';
$results = $this->dbc->runQuery($query, $this);
}
$userID = "1";
$test = new User;
$test->selectUser($userID, $test);
I run the initial setup of user then try to load it with the values retrieved in the datamanager. I understand that the PDO is an object itself but I am trying to still create a general interaction because this code will be expanded upon to allow more then the user object to access the database.
Here’s my version.
I added a
WHERE user_id=:idto your query and changed the pdo to useprepare().