2013-08-24 347 views
0

我想在我的web開發項目中實現PHP鏈接方法。但我似乎無法做到。PHP鏈接:如何從MySQL表中獲取數據?

class foo extends base{ 


    public $query = null; 
    public $item = array(); 

    public function __construct($connection){ 
     parent::__construct($connection); 

    } 

    public function select($query){ 
     $this->query = $query; 
     return $this; 
    } 

    public function where($query){ 
     $this->query = $query; 
     return $this; 
    } 

    public function __toString() 
    { 
     $this->item = $this->connection->fetch_assoc($this->query); 

     return var_export($this->item, true); 
    } 


} 

$connection = new db($dsn = 'mysql:host=localhost;dbname=xxx',$username = 'xxx',$password = 'xxx'); 
$foo = new foo($connection); 

$select = $foo->select("SELECT * FROM page")->where("page_id = 10 "); 
print_r($select->item); 

結果我得到的,

Array 
(
) 

但我應該得到的數據行。就像我通常這樣做,

class boo extends base{ 

    ... 

    public function select() { 

     $sql = " 
      SELECT * 
      FROM page 
      WHERE page_id = ? 
     "; 

     $item = $connection->fetch_assoc($sql,array(1)); 
     return $item; 

    } 
} 

我在鏈接方法中錯過了什麼?

編輯:

class base 
{ 
    protected $connection = null; 

    public function __construct($connection) 
    { 
     $this->connection = $connection; 

    } 


} 

,如果我只是打印$select

print_r($select); 

結果,

foo Object 
(
    [query] => where page_id = 10 
    [item] => Array 
     (
     ) 

    [connection:protected] => db Object 
     (
      [connection] => PDO Object 
       (
       ) 

      [dsn] => mysql:host=localhost;dbname=xxx 
      [username] => xxx 
      [password] => xxx 
     ) 

) 

回答

0

嘗試像

$select = $foo->select('*')->from('page')->where('page_id','10'); 
print_r($select); 
0

通過以下調用所有你正在做的是設置和更換foo類的$query成員變量的值:

$select = $foo->select("SELECT * FROM page")->where("page_id = 10 "); 

所以,$foo->select("SELECT * FROM page")設置$query成員變量的值,然後->where("page_id = 10 ")替換值。

另外,您沒有執行查詢。

+0

謝謝。我該如何鏈接查詢並執行它呢? – laukok

+0

你的「基地」是如何實施的?你也可以在你的問題中提出這個問題嗎?嘗試打印只是像'print_r($ select)'而不是'print_r($ select-> item)'' – vee

+0

'base'只是爲了保持數據庫連接的屬性。請看看我上面的編輯。感謝 – laukok