1

Greetings good people,

I am running with some issue with OOP recently. First, I am looking to create CRUD Db class from scratch. This is a code:

class  Database{

    public static $link;
    public $message;
        public function __construct () {

        try {
            self::$link = mysqli_connect(HOST, USER, PASS, DB);

            if (!self::$link) {
                echo self::$link->error;
            }


        } catch (Exception $e) {
            die(" Failed connecting to DB") ;
        }
    }

    public static function query($SQL){

        return self::$link->query($SQL);

    }
        public static function select($table, array $columns){
        $columns=implode(",",$columns);
        $result=self::query("SELECT $columns FROM $table");


        return self::$link->fetch($result);
    }

}

So the problem is this:

If I call my static select function like this:

Database::select('users', array('username'=>'user')); 

It returns: Fatal error: Call to a member function query() on a non-object in .. And if I debug connection like this: var_dump(Database::$link) it returns NULL But if I place "$db = new Database();" above that line, it works?

Can anyone instruct me what I am doing wrong?

Thanks!

fugitive
  • 357
  • 2
  • 8
  • 26

1 Answers1

1

You are calling a static method. So, the object WILL NOT be instantiated. So, __construct() method WILL NOT be called. Which means $link property will not be populated.

Whatever you do, you need to connect to your DB. You can either call a static method connect() which will connect to database and populate $link, or make sure in every method that require the connection, that the connection is established:

public static function connect()
{
    try {
        self::$link = mysqli_connect(HOST, USER, PASS, DB);
        if (!self::$link) {
            echo self::$link->error;
        }
    } catch (Exception $e) {
        die(" Failed connecting to DB") ;
    }
}

public function select(SQL)
{
    if (!static::$link) {
        static::connect();
    }

    // your stuff

}

It's a good thing you want to learn. Before dealing with specific projects like that, you need to be comfortable with OOP: constructors/destructors, accessors, mutators, static methods, etc. It's important since it's the basis of all what you will want to do next.

Arcesilas
  • 1,388
  • 11
  • 24
  • @YourCommonSense I understand that MilosM wants to learn. The main problem here is not database usage, it's understanding the OOP principles. – Arcesilas May 12 '16 at 11:54
  • @Arcesilas Thanks for a clear explanation! I thought that calling statically Database will make an instance because its db object is created in constructor and so $link will hold DB object Thanks again for a help ;) – fugitive May 12 '16 at 11:57