2011-03-18 125 views
3

我想做一個函數查詢數組,然後我將能夠調用單獨的值。在這裏,我想你會明白我在做什麼。除了我是一個完整的初學者。php oop和mysql查詢

class Posts{ 

    var $title; 
    var $author; 

    public function querySinglePost($value){ 

    $post = mysql_fetch_array(mysql_query("select * from posts where id=$value")); 
    $this->title = $post['title']; 
    $this->author = $post['author']; 

    } 


} 

如何將數組值分配給類中的變量,然後在我的普通php腳本/視圖中調用它們?由於

回答

5

看看mysql_fetch_object。 我也建議使該函數靜態,這將返回創建的對象。就像這樣:

class Posts{ 

    var $title; 
    var $author; 

    public static function querySinglePost($value){ 

    return mysql_fetch_object(
     mysql_query("select * from posts where id=$value"), 
     __CLASS__); 

    } 

} 

$post = Posts::querySinglePost($value); 
$a = $post->title; 
//... 
+0

如果你正在重構整個事情,不妨拋出一些錯誤/空結果集處理。 +1「獲得」OP後的內容(我認爲) – Phil 2011-03-18 14:59:55

+0

我愛你Slava ......你知道嗎?這工作完美。謝謝! – Chris 2011-03-18 15:07:25

1

除了沒有任何錯誤處理,不會你只是做類似

$posts = new Posts; 
$posts->querySinglePost(1); 
echo $posts->title; 
echo $posts->author; 
+0

此外,PHP 4死了很久很久以前。 – Phil 2011-03-18 14:57:19

1
$posts = new Posts(); 
$posts->querySinglePost($id); 

echo "return values: \n"; 
echo $posts->title . "\n"; 
echo $posts->author . "\n"; 
0
class Posts{ 

    public $post = array(); 

    public function querySinglePost($value){ 

    // fetch... $results 

    $this->post['title'] = $results['title']; 
    $this->post['author'] = $results['author']; 
    // ... 
    return $this->post; 
    } 
} 

$mySweetPost = new Posts(); 
print_r($mySweetPost->querySinglePost(1)); 
0

你可以在這種情況下,位更有條理。將此類考慮爲將擴展基本模型類的模型。而不是直接使用mysql_query,而是使用數據庫類並使用它可以執行數據庫操作,如查詢數據庫。插入到數據庫等,將其設置爲您的基礎模型類中的數據庫對象。作爲一個簡單的演示

class model{ 
    public function __construct() 
    { 
    $this->db = new Database(HOST,USER,PASS,DB); 
    } 
} 

class Post extends model{  
public $post; 
public function querySinglePost($value){ 
     $this->post = $this->db->query("select query"); 
     return $this->post; 
    } 
} 

您將調用像

$ObjPost = new Post(); 
$post = $ObjPost->querySinglePost(1);