2014-12-19 31 views
0

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

请停止使用'mysql_ *'函数:http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php – Mave 2014-12-19 09:28:52

+2

欢迎来到SO!在这个主板上,我们修复了不起作用的代码(错误的结果,错误等)。如果您只是在寻找如何让代码更好的建议,我们的[代码审查](http://codereview.stackexchange.com/)网站就是适当的地方。 – georg 2014-12-19 09:35:49

+0

应该在http://codereview.stackexchange.com/ – symcbean 2014-12-19 09:40:10

回答

0

使用getter和setter方法的关键在于,通过强迫开发者使用这些你可以实现更复杂的访问机制,例如设定当值设置让你的类就知道它写回一个标志插入到数据库中(尽管这是一个相当不好的例子,因为无需通过方法强制访问即可实现目标)。

BTW

news_id = '$this->newsArticleID' 

数字不应该被引用(打破了优化)和字符串应该在要在查询中使用的点进行转义。

+0

感谢您的信息,我将删除报价。 – Ruben 2014-12-19 10:48:29

0

我的建议是开始使用PHP-PDO和MySQL的存储过程。虽然在php代码中使用直接查询和使用存储过程(差别为几毫秒)时您会看到一个小的时间差异,但您将使用较少的代码在php中编写代码。以我的观点,你会有更平衡的应用程序。还可以使用getData和setData函数,它们应该以数组或者json的形式返回任何你想要的东西(我想如果你想使用浏览器的本地存储,你会发现这很有趣)。

+0

感谢您的信息。 – Ruben 2014-12-19 10:49:24