Tim C
Tim C

Reputation: 5714

PHP OOP avoid having to repeat similar queries in methods

Im learning, and am still struggling to get the hang of many OOP concepts so please keep that in mind when reading / answering the question.

So one of the primary purposes of object orientated programming is not to repeat yourself right. However, when I am creating methods, I constantly find myself repeating the same statements when querying the database. As can be seen in the below code taken from class I created.

 function getCategory()
    {
        $sql = "SELECT * FROM jobs";
        $stmnt = $db->prepare($sql);
        $stmnt->execute();
        $results = $stmnt->fetchAll();

        foreach ($results as $result) {
            $cat[] = $result['category'];
        }
        return  $this->category = $cat
    }
    function selectCategory($selectedCategory){
        $sql = "SELECT * FROM jobs
        WHERE  category =:category";
        $stmnt = $db->prepare($sql);
        $stmnt->bindValue(':category', $selectedCategory);
        $stmnt->execute();
        $results = $stmnt->fetchAll();
        foreach($results as $result){
            $result= array('category' => $result['category'], 'headline' => $result['headline']);
        }
        return $this->category = $result
    }// selectCategory

My question.

Is there a way / what should I do to avoid having to continuously write the same database queries in my methods? I feel im a little out of depth here, however its not going to stop me from trying. Any help, advice welcomed (please keep in mind im a beginner)

Upvotes: 2

Views: 176

Answers (1)

meda
meda

Reputation: 45500

You can run the query to get all data, then extract the data from fetched data using PHP.

But I don't like it, and it is not efficient.

You have 2 different query , so you need to calls, just improve your code a little more, you can make a model like this:

class Category
{
    private $db;

    public function __construct(PDO $db)
    {
        $this->db = $db;
    }


    function getAll()
    {
        return  $this->db->query('SELECT * FROM jobs');
    }

    function getByCategory($category){
        $stmt = $this->db->prepare(
            "SELECT * FROM jobs WHERE  category =:category"
        );
        $stmt->bindValue(':category', $category);
        $stmt->execute();
        return $stmt->fetchAll();
    }
}

This is perfectly fine, and it is not really repeating

Upvotes: 2

Related Questions