Kyubeh2435436
Kyubeh2435436

Reputation: 123

PHP PDO - How Can I Do This

I need a way to either do 4 queries or do make my $views variable be able to like switch from grabbing the highest view count to the 2nd highest view count etc and I need them to be formatted like an array so $views[0]; is the 1st highest view count and $views[4]; is the 4th highest count.

Code:

//Load Database Details
    require_once 'functions/db/dbconfig.php';

    //Database Connect - View - High - 1
    $db = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

    //Query and Fetch
    $res = $db->prepare("SELECT * FROM tvinfo ORDER BY views LIMIT 0, 1;");
    $res->setFetchMode(PDO::FETCH_ASSOC);
    $res->execute();
    $Result = $res->fetchAll();

    //Result Variables
    foreach ($Result as $r) {
        $name = $r['name'];
        $rating = $r['rating'];
        $imdbid = $r['imdbid'];
        $genre1 = $r['genre1'];
        if(!empty($r['genre2'])){ $genre2 = '- '.$r['genre2']; }
        $year = $r['year'];
        $views = $r['views'];
    }

Upvotes: 0

Views: 39

Answers (1)

Dipen Shah
Dipen Shah

Reputation: 1919

Untested but should work.

require_once 'functions/db/dbconfig.php';

//Database Connect - View - High - 1
$db = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

//Query and Fetch
$res = $db->prepare("SELECT * FROM tvinfo ORDER BY views DESC LIMIT 4;");
$res->setFetchMode(PDO::FETCH_ASSOC);
$res->execute();
$Result = $res->fetchAll();
//Result Variables
$views = array();
foreach ($Result as $r)
{
    $name = $r['name'];
    $rating = $r['rating'];
    $imdbid = $r['imdbid'];
    $genre1 = $r['genre1'];
    if(!empty($r['genre2'])){ $genre2 = '- '.$r['genre2']; }
    $year = $r['year'];
    $views[] = $r['views'];
}

var_dump($views);

Upvotes: 1

Related Questions