我有什么是在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