How to show data from mysql database in decending order using pdo?

I am trying to show data using “fetch(PDO::FETCH_desc” for show from descending order but it only works for assoc order like bellow code, how I can show it in descending order? I am new to php and pdo, please help.
[php]
$stmt = $DB_con->prepare(" SELECT name, id FROM class ORDER BY id DESC LIMIT 1, {$recordsPerPage}");
$stmt->execute();
echo $name;

if($stmt->rowCount() > 0)
   
{
    while($row=$stmt->fetch(PDO::FETCH_ASSOC))
    
    {
        extract($row);
        
        echo $name;
        
    }
}

[/php]

That isn’t what FETCH_ASSOC means. Fetch Association, not ascending.

If you want to change the sort order, you do so in the sql query.

[php]<?php

class dbc {

public $dbserver = 'server';
public $dbusername = 'user';
public $dbpassword = 'pass';
public $dbname = 'db';

function openDb() {    
    try {
        $db = new PDO('mysql:host=' . $this->dbserver . ';dbname=' . $this->dbname . ';charset=utf8', '' . $this->dbusername . '', '' . $this->dbpassword . '');
    } catch (PDOException $e) {
        die("error, please try again");
    }        
    return $db;
}

function getAllData($qty) {
    //prepared query to prevent SQL injections
    $query = "select * from TABLE where qty = ?";
    $stmt = $this->openDb()->prepare($query);
    $stmt->bindValue(1, $qty, PDO::PARAM_INT);
    $stmt->execute();
    $rows = $stmt->fetchAll(PDO::FETCH_DESC);
    return $rows;
}    

?>[/php]

That to me would create a danger of having too many instances of Database Connections open. Just my opinion.

Other than splitting things into functions, I see no benefit to that at all. If you want to go the function call way, using a class and models would be the correct way to move to anyway.

Sponsor our Newsletter | Privacy Policy | Terms of Service