douchi5822 2014-12-19 09:28
浏览 23

如何在类中使用sql查询

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
    }
}
  • 写回答

2条回答 默认 最新

  • douhan9467 2014-12-19 09:38
    关注

    The point of using setters and getters is that by forcing the developer to use these you can implement more complex access mechanisms, for example setting a flag when a value is set so that your class knows to write it back into the database (although this is a rather bad example as the objective can be acheived without having to force access via a method).

    BTW

    news_id = '$this->newsArticleID'
    

    No.

    Numbers shouldn't be quoted (breaks the optimizer) and strings should be escaped at the point where they are used in a query.

    评论

报告相同问题?

悬赏问题

  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上