簡體   English   中英

php oop和mysql查詢

[英]php oop and mysql query

我正在嘗試創建一個查詢數組的函數,然后我將能夠調用單獨的值。 在這里,我想你會理解我想要做的事情。 除了我是一個完整的初學者。

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腳本/視圖中調用它們? 謝謝

看看mysql_fetch_object 我還建議將該函數設為static,它將返回創建的對象。 像這樣:

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;
//...

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

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

echo "return values: \n";
echo $posts->title . "\n";
echo $posts->author . "\n";
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));

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

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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM