2011-10-31 65 views
0

我有這樣的代碼,從i-net類下載db。 我很感興趣,我可以如何在構造函數中進行連接,以便我不會像現在這樣在每種方法中連接db。但我得到了很多錯誤,這裏是代碼:db在php中連接

<?php 
include_once('mysqldatabase.php'); 
include_once('mysqlresultset.php'); 
class Car 
{ 
    public $marka; 
    public $model; 
    public $engineVol; 
    public $VIN; 
    public $engineType; 
    public $transmission; 
    public $bodyType; 
    public $other; 
    public $clientCode; 
    public $code; 

    public function __construct() 
    { 


    } 

    public function viewCar($id) 
    { 
     $db = MySqlDatabase::getInstance(); 
     try { 
      $conn = $db->connect('localhost', 'root', '', 'discont'); 
     } 
     catch (Exception $e) { 
      die($e->getMessage()); 
     } 
     echo "view <br> "; 
     $query = 'SELECT * FROM car Where Code = '.$id.''; 
      foreach ($db->iterate($query) as $row) { 
      echo "<br>"; 
      echo "~".$row->Marka; 
     } 
    } 

    public function addCar() 
    { 
     echo "add"; 
     $db = MySqlDatabase::getInstance(); 
      try { 
      $conn = $db->connect('localhost', 'root', '', 'discont'); 
     } 
     catch (Exception $e) { 
      die($e->getMessage()); 
     } 

      $query = "SELECT * FROM car"; 
     foreach ($db->iterate($query) as $row) { 
      echo "<br>"; 
      echo $row->Marka; 
     } 
    } 
} 

?> 

sory對於我,也許,愚蠢的問題。但我真的不知道(

+0

你會得到什麼錯誤? – middus

回答

1

如何聲明一個類變量$db

private $db; 

移動這個代碼viewCar()的構造器:

$this->db = MySqlDatabase::getInstance(); 
try { 
    $conn = $this->db->connect('localhost', 'root', '', 'discont'); 
} 
catch (Exception $e) { 
    die($e->getMessage()); 
} 

取下addCar重複的代碼()最後將viewCar()addCar()中的參考文獻從$db更新爲$this->db

+0

謝謝)這很好 – DPS