我可以执行SELECT查询而不重复自己吗?

时间:2019-06-29 10:49:05

标签: php oop

是否可以通过第二种方法执行查询而无需重复上述所有内容? 还是应该将所有内容合并为一个函数?

public function selectAd()
    {
        $query = "
            SELECT category,title,content,date_added from ads
        ";
        $stmt = $this->getConnection()->prepare($query);
        $stmt->execute();
        $count = $stmt->rowCount();
        if ($count > 0) {
            $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
            foreach ($result as $row) {
                echo '<div class="result">';

                echo "Title: <b>".$row['title']."</b>";
                echo "<h6>Category:".ucfirst($row['category'])."</h6>"
                .$row['content']."<br>".
                "Date: ".$row['date_added'];

                echo '</div>';
                echo "<br>";
            }
        } else {
            echo "<u><br>Nothing to show yet</u>";

        }
    }

    public function randomAds()
    {
        $query = "
        SELECT * FROM ads ORDER BY RAND() LIMIT 5;
        ";
        // steps from method above

    }

1 个答案:

答案 0 :(得分:-1)

考虑一下:

public function WriteOutAds($doShowThemAll)
{
   $query = 'SELECT category, title,content, date_added FROM ads';
   if ($doShowThemAll==false)
      $query .= ' ORDER BY RAND() LIMIT 5'; //Display only 5 random ones
   //perform your query
   //do emit the result
}