我有什麼是在PHP類中實現SQL查詢的最佳方式的問題。我想保持儘可能低的查詢。如何在類中使用sql查詢
這是我第一次嘗試:
class NewsArticle
{
//attributes
private $newsArticleID;
//methodes
//constructoren
public function __construct($newsArticleID)
{
$this->newsArticleID = $newsArticleID;
}
//getters
public function getGeneralData()
{
$query = mysql_query("SELECT author, title, content, datetime, tags FROM news WHERE news_id = '$this->newsArticleID'");
$result = mysql_fetch_array($query);
$data = array(
'author' => $result['author'],
'title' => $result['title'],
'content' => $result['content'],
'datetime' => $result['datetime'],
'tags' => $result['tags']
);
return $data;
}
//setters
}
現在我知道這將是更好的創造generalData,並對每個項目二傳手我從數據庫中檢索創建一個變量,並指定合適的值。然後我可以爲每個變量創建一個getter。所以這樣。
class NewsArticle
{
//attributen
private $newsArticleID;
private $author;
private $title;
// more variables
//methodes
//constructoren
public function __construct($newsArticleID)
{
$this->newsArticleID = $newsArticleID;
}
//getters
public function getAuthor()
{
return $this->author;
}
public function getTitle()
{
return $this->title;
}
//setters
public function setGeneralData()
{
$query = mysql_query("SELECT author, title, content, datetime, tags FROM news WHERE news_id = '$this->newsArticleID'");
$result = mysql_fetch_array($query);
$this->author = $result['author'];
$this->author = $result['author'];
//other variables
}
}
請停止使用'mysql_ *'函數:http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php – Mave 2014-12-19 09:28:52
歡迎來到SO!在這個主板上,我們修復了不起作用的代碼(錯誤的結果,錯誤等)。如果您只是在尋找如何讓代碼更好的建議,我們的[代碼審查](http://codereview.stackexchange.com/)網站就是適當的地方。 – georg 2014-12-19 09:35:49
應該在http://codereview.stackexchange.com/ – symcbean 2014-12-19 09:40:10