<?php
class User {
// properties
public $table = 'users';
public $id;
public $username ;
public $password ;
public $first_name ;
public $last_name ;
Above (id, username…, last_name) are the column of users table in MySQL Database. After fetching(I’m using PDO) a specific record from users table using id, how can I assign all records to their respective properties dynamically(a function may help that will search through all available properties and search those properties in the resulting associative array and then assign those specific values to their respective properties)?
// methods
public function set_user($id){
global $dbh;
// sql
$sql = "SELECT * FROM $this->table WHERE id = {$id}";
// return result array
$result_arr = $dbh->pdo_query_fetch($sql);
}
$result_arr contains associative array of id, username, password, first_name and last_name.
NOTE : Here pdo_query_fetch() is a user-defined function.
You’re using PDO, it has that with
PDO::FETCH_INTO:See PDO::queryDocs.
It might be that your “own” database class then is “owning” you, because you started to encapsulate things too early. This might require you to add an additional function to your
$dbhclass and/or you might want to start to refactor.