Motombo
Motombo

Reputation: 1787

Implementing mysqli procedural with a class

so recently I've been trying to use more procedural mysqli for practise, and have been looking at http://www.phpknowhow.com/mysql/mysqli-procedural-functions/, and also w3schools as reference, but i'm still having trouble so I thought I'd ask.

I have this database.php file where I have alot of stuff but the important stuff is

class Database{
    public $host = DB_HOST;
    public $username = DB_USER;
    public $password = DB_PASS;
    public $db_name = DB_NAME;

    public $link; 
    public $error;

   public function __construct(){

       $this -> connect();
   }

    private function connect(){

       $link = mysqli_connect($this->host,$this->username,$this->password,$this->db_name);
        if(!$link){
            echo "Failed".mysqli_error($link);
        }
    }



    // create select method

    public function select($query){
        $result = mysqli_query($link,$query) or die("didnt work".mysqli_error($link));
        if(mysqli_num_rows($result) > 0){
            return $result;
        }
        else{
            return false;
        }
    }

Now the way it currently works fine in my index.php file is simply by doing something like

$db = new Database();

//CREATe query
$query = "SELECT * FROM posts";
$posts = $db->select($query);

Is there any way to implement $posts = $db->select($query) with procedural functions? Before I have done stuff like mysqli_query($link,$query), but link is public here and inside a class so I can't do that, plus I want to access the function select . Thanks!

Upvotes: 0

Views: 366

Answers (1)

Jocelyn
Jocelyn

Reputation: 11413

$link is not defined in your function select.

Modify your connect function:

private function connect() {
    $this->link = mysqli_connect($this->host, $this->username, $this->password, $this->db_name);
    if(!$this->link) {
        echo "Failed: " . mysqli_error($this->link);
    }
}

Now $this->link may be used in your select function:

public function select($query){
    $result = mysqli_query($this->link, $query) or die("didn't work: "  .mysqli_error($this->link));
    if(mysqli_num_rows($result) > 0) {
        return $result;
    }
    else{
        return false;
    }
}

I suggest you read the PHP OOP documenentation (at least the first chapters) to get a better understanding.

Upvotes: 2

Related Questions