0

I'm still playing around with classes and can't get this one running:

class db_connection {
    private $dbc;


    public function __construct()
    {
        $this->dbc = new mysqli(HOST_ONE, USER_ONE, PASS_ONE, DB_ONE);

    }

    public function getDbc()
    {
        return $this->dbc;
    }

}

class db_query extends db_connection{
    private $querystring;

    private $result;

    function __construct ($table, $field) {
        $this->querystring = $query = parent::getDbc()->query("SELECT ".$field." FROM ".$table);
        $this->result = $row = $query->fetch_assoc();
    }
    function get_resultset() {
        return $this->result;
    }
}

this is how I try to run it:

$db_conn = new db_connection();
$db = $db_conn->getDbc();

$action = new db_query('datenbanken','id');
$result = $action->get_resultset();
var_dump($result);

The connection is established without any problems, but it won't query the database with my class.

I won't to achieve that I can run a query and only have to set

$action = new db_query('datenbanken','id'); 

this line...

Can someone help me on how I can solve this? Thanks!

1 Answer 1

2

you need to call parent constructor when overriding the class you extend, so in this case

class db_query extends db_connection{
    private $querystring;

    private $result;

    function __construct ($table, $field) {
        parent::__construct(); // now we have $this->dbc constructed
        $this->querystring = $query = $this->getDbc()->query("SELECT ".$field." FROM ".$table);
        $this->result = $row = $query->fetch_assoc();
    }
    function get_resultset() {
        return $this->result;
    }
}

note that parent keyword is only used if you want to call the function from the class that you extend

in your case $this gets populated, so there is no need to use parent::getDbc(), instead you should use $this->getDbc()

however if you were overriding getDbc you would have:

class my_other_class extends db_connection{

    function getDbc() {
        // call parent funct
        $res = parent::getDbc();
        $res = doSomethingWithRes($res);
        return $res;
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Might as well remove the unused $query and $row variables as well
Excellent, that works for one row. Thank you! Shall I do the while loop inside the class or when running the class?
i leave the design of your database driver to your imagination, however if i were you i would look into some most popular ORMs such as en.wikipedia.org/wiki/Doctrine_(PHP) and for something simpler you can look into github to find some lightweight open source library from which you can learn / improve

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.