2012-07-13 35 views
2

我想知道爲什麼我的代碼出現錯誤?有人可以幫忙嗎? 我的班是讓使用嵌套方法數據庫的一些信息,假設我得到一個空的查詢是嵌套的方法嗎?爲什麼我得到空查詢?

<?php 
class db { 
public function __construct(){ 
if(mysql_connect("localhost","root","0000")){ 
    mysql_select_db("myblog"); 

}else{ 
    echo mysql_error(); 
} 

} 

    public function select($row){ 
     $sql="SELECT".$row; 
     return $this; 
    } 

    public function from($table){ 
     $sql.="FROM".$table; 
     return $this; 
    } 

    public function where($condition){ 
    $sql.="WHERE".$condition; 
     return $this; 
    } 

} 
$ddb=new db; 
$qq=$ddb->select("*")->from("news")->where("id='1'"); 
$query= mysql_query($qq); 
while($row=mysql_fetch_object($query)){ 
    echo $row->title; 
} 
?> 
+0

添加調試到你的每一個方法,讓你知道他們是什麼返回。回覆完成的聲明,以便看到它的外觀。 – andrewsi 2012-07-13 13:27:17

+3

你的查詢最終沒有空格......'SELECT * FROMnewsWHEREid = 1' – rsplak 2012-07-13 13:29:09

+0

@rsplak,實際上,mysql_query()在這段代碼中甚至沒有字符串。 – 2012-07-13 13:38:42

回答

1

你必須定義__toString()特殊的方法來使用你的對象作爲一個字符串:

class db { 

    private $sql = ''; 

    public function __construct() { 
     if (mysql_connect("localhost", "root", "0000")) { 
      mysql_select_db("myblog"); 
     } else { 
      echo mysql_error(); 
     } 
    } 

    public function select($row) { 
     $this->sql = "SELECT ".$row; 
     return $this; 
    } 

    public function from($table) { 
     $this->sql .= " FROM ".$table; 
     return $this; 
    } 

    public function where($condition) { 
     $this->sql .= " WHERE ".$condition; 
     return $this; 
    } 

    public function __toString() { 
     return $this->sql; 
    } 

} 

$ddb = new db(); 
$qq = $ddb->select("*")->from("news")->where("id='1'"); 
$query = mysql_query($qq); 
while ($row = mysql_fetch_object($query)) { 
    echo $row->title; 
} 
1

你需要在每個方法使用$this追加到$sql

// Declare the class property 
    public $sql = ""; 


    // And use $this->sql in the methods 
    // Also note whitespace added around SELECT, FROM, WHERE 
    public function select($row){ 
     $this->sql="SELECT ".$row; 
     return $this; 
    } 

    public function from($table){ 
     $this->sql.=" FROM ".$table; 
     return $this; 
    } 

    public function where($condition){ 
    $this->sql.=" WHERE ".$condition; 
     return $this; 
    } 

然後當你查詢它時,使用$ddb->sql,因爲你沒有返回SQL字符串。

$ddb->select("*")->from("news")->where("id='1'"); 
$query = mysql_query($ddb->sql); 

而且它不用說,希望你打算要調用你構造的變量mysql_real_escape_string()到您的where()方法。事實上,你沒有特別的逃避。

0

在$ QQ

這會立即顯示你的問題運行的var_dump。

在我看來,如果你在你的DB類

+0

這對我來說是有用的檢測錯誤,但沒有解決所有問題,謝謝 – user1523523 2012-07-13 16:29:34

0
  • 使用$this->sql失蹤一對夫婦的空間在您的查詢,你沒有返回查詢字符串$ sql中,而是$這個,而不是$sql在方法selectfromwhere
  • 輸出該查詢是這樣的:$ddb->select("*")->from("news")->where("id='1'")->sql或創建getSQL()方法,該方法僅返回$sql字段和查詢它像$ddb->select("*")->from("news")->where("id='1'")->getSQL()

您還應該考慮創建一個創建mysql_query(不僅是字符串)或用於檢索方法的一些方法的方法,因此它更易於使用。