开发者

OO database class

开发者 https://www.devze.com 2023-01-05 04:12 出处:网络
I\'m trying to learn object oriented programming more clearer by creating a database class in PHP. This is what i have right now. I\'m getting an error about $mysqli being an undefined variable when

I'm trying to learn object oriented programming more clearer by creating a database class in PHP.

This is what i have right now. I'm getting an error about $mysqli being an undefined variable when i try to call it using $db->query();

Please explain how to make the variable $mysqli defined.

<?php

class phpDatabaseC开发者_运维问答lass {

 public function __construct()
 {
  $mysqli = new mysqli(DBhost, DBusername, DBpassword, DBname);
 }

 public function query()
 {
  $sql = 'select * from users';
  $results = $mysqli->query($sql);

  if(($results->num_rows) > 0) 
  {
   echo 'We have: '.$results->num_rows;
  }
 }

}

?>

In another file i am instantiating the object and then calling a function like this:

 require 'phpDatabaseClass.php';
 define('DBhost', 'localhost');
 define('DBusername', 'root');
 define('DBpassword', 'root');
 define('DBname', 'campbellCustomCoatings');


 $db = new phpDatabaseClass();
 $db->query();


Your instance of mysqli will need to be a member of your class, have a look here...

class phpDatabaseClass {
 private $mysqli;
 public function __construct()
 {
  $this->mysqli = new mysqli(DBhost, DBusername, DBpassword, DBname);
 }

 public function query()
 {
  $sql = 'select * from users';
  $results = $this->mysqli->query($sql);

  if(($results->num_rows) > 0) 
  {
   echo 'We have: '.$results->num_rows;
  }
 }

}

Also, because you are learning, try extending the PDO class to learn about inheritance.

Also, slightly tangential, but generally constants are named with ALL_CAPS_WITH_UNDERSCORE_SEPARATORS.

Also, database stuff in global defines can be risky, as every piece of PHP can access it. I know WordPress does it, but trust me that the quality of its code is questionable. Its popularity however, is without doubt huge.


The problem I can see is trying to make $mysqli persist between function calls inside the same object.

What needs to be done is to have the variable stored as an instance variable, which are qualified by $this->[VARIABLE]:

<?php

class phpDatabaseClass {

 public function __construct()
 {
  $this->mysqli = new mysqli(DBhost, DBusername, DBpassword, DBname);
 }


 public function query()
 {
  $sql = 'select * from users';
  $results = $this->mysqli->query($sql);

  if(($results->num_rows) > 0) 
  {
   echo 'We have: '.$results->num_rows;
  }
 }

}

?>

I'd look into using PDO.

0

精彩评论

暂无评论...
验证码 换一张
取 消