Question

I have a class name db_access that is extended to db_connection which is running the query; my class db_access has a method named result, you can see I just echo the property name query inside my classes, and it runs ok. Now my problem is in the db_connection, how can I run my host connection automatically inside the constructor? I done function named connect() and call that inside the run() ,but i want it to be automatically run, (by the way that db_access is extended from some class also) Please help.

class db_access extends db_connection
{       
    public function result()
    {           
                echo $this->query;
            $this->run();           

    }       
}


class db_connection{    
      private $link;      

      public function __construct() {    
        $this->link=mysql_connect('localhost','root','') or die(mysql_error());         
        mysql_select_db('jsample');
      }

    public function run(){
        echo $this->query;
        mysql_query($this->query) or die(mysql_error());    
    }       
} 

No correct solution

OTHER TIPS

You don't ever set the "query" property. So I think you left out some code. I'll bet you also left out a __construct for db_access. In PHP, you have to manually chain up your constructors. So inside db_access::_construct you need to call parent::_construct()

See the PHP documentation on __construct.

For one, in your db_connection::run() you should pass $this->link to mysql_query:

public function run()
{
    echo $this->query;
    mysql_query($this->query, $this->link) or die(mysql_error());    
}

Second, you should check whether mysql_select_db() returned true or false:

if (false === mysql_select_db('jsample', $this->link)) {
    die("Could not select database");
}

Third, where are you setting $this->query?

Lastly, you should use PDO or mysqli instead. The mysql_ family function has been deprecated and will eventually be removed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top