I have a question on what is the best way of implementing SQL queries in PHP classes. I want to keep the queries as low as possible.
This was my first attempt:
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
}
Now I'm wondering if it would be better to create a setter for generalData and for each item I retrieve from the database create a variable and assign the proper value. Then I could create a getter for each variable. So like this.
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
}
}