Varin
Varin

Reputation: 2443

How to fetch all columns from DB to a model using PDO, apart from selected columns?

In Laravel you can declare some properties in the model which will not be fetched, how to do this in pure PHP / SQL? My controller method looks like this:

public function getUserByUsername($username)
{

    $db = new Db();

    $query = $db->conn->prepare("SELECT id, userName, firstName, lastName, phoneNumber, userType, compliant, emailVerified, phoneVerified FROM apiAccount WHERE userName = :userName");
    $query->bindParam(':userName', $username);

    if($query->execute())
    {
        $db = null;
        $query->setFetchMode(PDO::FETCH_CLASS, 'AccountModel');
        $result = $query->fetchAll();
        if (isset($result[0])) {
            $db = null;
            return $result[0];

        } else {
            $db = null;
            throw new APIException('Query could not be executed, user not found', 600, null, 'User does not exist');
        }
    }
    else
    {
        $db = null;
        throw new APIException('Query could not be executed', 600, null, 'Dodgy SQL');
    }
}

And my model:

class AccountModel extends BaseModel
{
    public $id;
    public $userName;
    public $firstName;
    public $lastName;
    public $phoneNumber;
    public $userType;
    public $compliant;
    public $emailVerified;
    public $phoneVerified;
}

Basically, I don't want to constantly add stuff to my query every time I add or amend the column in the database. I just really want to skip password being fetched automatically when I fetch the user info into my model. Please point me in the right direction.

Upvotes: 0

Views: 47

Answers (1)

Don't Panic
Don't Panic

Reputation: 41810

One way is to add a constructor to your model that takes an array and only sets its properties that exist.

function __construct($properties = []) {
    foreach ($properties as $key => $value) {
        if (property_exists($this, $key)) $this->$key = $value;
    }
}

Then fetch an associative array and construct the instance of the model from that.

if($query->execute())
{
    $db = null;
    $result = $query->fetch(PDO::FETCH_ASSOC);
    if ($result) {
        return new AccountModel($result);
    }
}

Upvotes: 1

Related Questions