0

I want to pull values from the DB and insert them into variables in a class.

IS the best and ideal way to just create a DB class and then reference that class within the main class to set the protected values to the values from the DB?

    if(!empty($S)){
        $_client_id=$S['API_ID'];
        $_client_secret=$S['API_PASSWORD'];
        $_client_id=$S['API_SECRET'];
        $_access_token=$S['API_TOKEN'];
        $_username=$S['API_USER'];
    }

class MyClass
{
    protected $_client_id = '20123123';
    protected $_client_secret = '76fesresg45grgerg3g34';
    protected $_username = 'letsHe'
4
  • This question is missing information, what database handler are you using? PDO, MySQLi? If PDO, look at PDO::FETCH_CLASS Commented Sep 7, 2016 at 14:43
  • MySQLi did not know that database handler was important in this case. Commented Sep 7, 2016 at 14:45
  • You should be handling this using a dependency injection model. That would be the proper way, if that's what you're looking for. A good write up on that with some basics to get you started can be found here: php-di.org/doc/understanding-di.html Commented Sep 7, 2016 at 14:45
  • 2
    Then the function would be mysqli_result::fetch_object Commented Sep 7, 2016 at 14:47

1 Answer 1

1

The best way is to use PDO's ability to manipulate objects.

Get rid of mysqli, and use PDO to get your objects right out of SQL:

class MyClass
{
    protected $client_id;
    protected $client_secret;
    protected $username
}

$sql = "SELECT * from my_class where id=1";
$myClassInstance = $pdo->query($sql)->fetchObject('MyClass');

$sql = "SELECT * from my_class";
$myClassCollection = $pdo->query($sql)->fetchAll(PDO::FETCH_CLASS, 'MyClass');

Note that unlike mysqli, PDO can let you provide constructor parameters, call setters, assign properties either before or after constructor call.

Sign up to request clarification or add additional context in comments.

5 Comments

And as var names are different from column names SELECT API_ID as client_id etc...
@AbraCadaver for this case you may define a magic __set() method that will do the appropriate modifications.
I think you refer to the method fetchObject(), since fetchClass() does not exist.
Sorry to bother again, the last line must be ´fetchAll(PDO::FETCH_CLASS, 'MyClass');` or it will not work.
@PhilippPalmtag damn me again you are right. I should think of the answer I am writing, not the job task at hand

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.