I'm trying to find out what is the right approach to return DB values from a class. This is what I came up with:
class Category {
public $result;
public $errors;
public function __construct( $pdo) {
$this->pdo = $pdo;
}
public function getCategoryNames () {
$sql = "SELECT category_id, category_name FROM category";
try {
$query = $this->pdo->prepare( $sql );
if( $query->execute( ) ) {
if( $query->rowCount() ) {
$this->result = $query->fetchAll();
return true;
}
return false;
}
return false;
} catch ( PDOException $pe ) {
trigger_error( 'SQL Error' . $pe->getMessage() );
}
}
public function getUserDetails($userid) {
$sql = "SELECT * FROM users WHERE user_id = :user_id";
try {
$query = $this->pdo->prepare( $sql );
if( $query->execute( array( 'user_id' => $userid ) ) ) {
if( $query->rowCount() ) {
$this->result = $query->fetch(PDO::FETCH_ASSOC);
return true;
}
return false;
}
return false;
} catch ( PDOException $pe ) {
trigger_error( 'SQL Error' . $pe->getMessage() );
}
}
$category = new Category($pdo);
$category->getCategoryNames();
print_r($result);
$category->getUserDetails('1');
print_r($result);
Is this approach good? Or what is the proper way to do this?