简体   繁体   中英

query mysql database by field and return all occurrences

I have a table in my database that has these fields:

-id
-video_title
-video_article
-video_category

Now, I'd like to query it by video_category and I have tried this code so far:

public function related_videos($current_video_category)
{
    $sql = "SELECT * FROM English WHERE video_category = :current_video_category";
    $stmt = $this->pdo->prepare($sql);
    $result = $stmt->execute(array(":current_video_category" => $current_video_category));
    $data = $stmt->fetch(PDO::FETCH_ASSOC);

    return $data;
}

The problem is it returns the first occurrence only and I'm not sure how to return all the occurrences of $current_video_category at once.

Any help would be really appreciated.

You only fetch one row:

$data = $stmt->fetch(PDO::FETCH_ASSOC);

If you want to fetch all available rows from the statement, use fetchAll :

$data = $stmt->fetchAll(PDO::FETCH_ASSOC);

This returns an array where each element is a row from the query.

You need to put that fetch assoc in while loop to get all data

While($data = $stmt->fetch(PDO::FETCH_ASSOC)){

//process data here

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM