2016-06-19 8 views
0

OO PHPデータベースクラスを作成しようとしていますが、$ dbconnect変数を 'select'メソッドに渡す方法が問題になります。以下は私のコードです:

class Database { 

private $db_host = "host"; 
private $db_user = "user"; 
private $db_pass = "password"; 
private $db_name = "dbname"; 
private $result = array(); 
private $myQuery = ""; 
private $numResults = ""; 

public function connect() { 

    $dbconnect = mysqli_connect($this->db_host, $this->db_user, $this->db_pass, $this->db_name); 
    if(mysqli_connect_errno()) { 

     array_push($this->result, mysqli_connect_error()); 
     return false; 

    } else { 

     $this->con = true; 
     return true; 

    } 

} 

public function select($table, $rows = '*', $join = null, $where = null, $order = null, $limit = null) { 

    $sql = 'SELECT '.$rows; 
    if($table) { 
     $sql .= ' FROM '.$table; 
    } 
    if($join != null) { 
     $sql .= ' JOIN '.$join; 
    } 
    if($where != null) { 
     $sql .= ' WHERE '.$where; 
    } 
    if($order != null) { 
     $sql .= ' ORDER BY '.$order; 
    } 
    if($limit != null) { 
     $sql .= ' LIMIT '.$limit; 
    } 

    $query = $dbconnect->query($sql); 
    $this->myQuery = $sql; 

    if($query->num_rows > 0) { 

     $this->numResults = $query->num_rows; 

     for($i = 0; $i < $this->numResults; $i++) { 

      $r = mysqli_fetch_array($query); 
      $key = array_keys($r); 
      for($x = 0; $x < count($key); $x++) { 

       if(!is_int($key[$x])) { 
        if(mysqli_num_rows($query) >= 1) { 
         $this->result[$i][$key[$x]] = $r[$key[$x]]; 
        } else { 
         $this->result = null; 
        } 
       } 

      } 

     } 
     return true; 

    } else { 

     //array_push($this->selectresult, 'No rows returned'); 
     return false; 

    } 

} 

私は$ dbconnect変数に割り当てるデータベース接続を作成する方法があります。私の問題は、私はmysqliを使用しているので、私はselectメソッド内でこの変数を取得できる必要があるということです...しかし、私の上記のコードではできません。私は次のエラーを取得する:

注意:未定義の変数:

DBCONNECTすべてのヘルプは、私が間違って行くよどこ素晴らしいことだと指摘します。

+0

1)この '$ this-> con = true;'は間違っています、あなたのクラスにインスタンスメンバー '$ con'がありません。 2)あなたは以下の2つの答えを与えられています。どちらもあなたのために働くはずです。 –

+0

ありがとう、良い点 – aboother

答えて

2

今あなたができる$this->dbconnect

+0

ありがとう、それは問題を解決した – aboother

2

としてあなたのクラスの残りの部分でそれを参照することができ、それ

$this->dbconnect = mysqli_connect($this->db_host, $this->db_user, $this->db_pass, $this->db_name); 

を初期化し、あなたのコンストラクタで、クラスのプロパティとして

private $dbconnect; 

それを宣言するこのクラスのプロパティを作成する

protected $dbconnect; 
その後、

、代わりにこのことができます$query = $dbconnect->query($sql);

希望の$dbconnect

public function __construct() 
{ 
    $this->dbconnect = mysqli_connect($this->db_host, $this->db_user, $this->db_pass, $this->db_name); 
} 

してからselect()関数を使用している

$query = $this->dbconnect->query($sql);の値を設定し、コンストラクタを作成します。