简体   繁体   中英

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'];
    }

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);

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