Problema ordonare in script paginare

Discutii despre script-uri si coduri PHP-MySQL, precum si lucru cu XML in PHP.
MelecaCristian
Mesaje: 176

Problema ordonare in script paginare

Buna, am urmatorul script de paginare, insa nu reusesc sa-l setez sa-mi returneze inregistrariile din mysql ordonate descendent dupa ID.

Am incercat sa adaug urmatorul "ORDER BY id DESC" cod la linile sql, dar nu functioneaza:

Cod: Selectaţi tot

  $sqlcount = "select count(*) as total_records from acasa ORDER BY id DESC";
   $sql = "select * from acasa limit :offset, :per_page ORDER BY id DESC";
  

Cod: Selectaţi tot

<?php
try {
  $pdo = new PDO("mysql:host=localhost;dbname=$dbname", "$username", "$password");
  $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES,false);

  /* Begin Paging Info */

  $page = 1;

  if (isset($_GET['page'])) {
    $page = filter_var($_GET['page'], FILTER_SANITIZE_NUMBER_INT);
  }

  $per_page = 10;

  $sqlcount = "select count(*) as total_records from acasa";
  $stmt = $pdo->prepare($sqlcount);
  $stmt->execute();
  $row = $stmt->fetch();
  $total_records = $row['total_records'];

  $total_pages = ceil($total_records / $per_page);

  $offset = ($page-1) * $per_page;

  /* End Paging Info */

  $sql = "select * from acasa limit :offset, :per_page";
  $stmt = $pdo->prepare($sql);
  $stmt->execute(['offset'=>$offset, 'per_page'=>$per_page]);

  echo "<table border='1' width='100%' overflow-x:auto; style='text-align: center; padding-left: 130px;'>";

  while ( ($row = $stmt->fetch(PDO::FETCH_ASSOC) ) !== false) {
    echo "<tr>";
    $myStr = $row['ip'];
    echo "<td>";
    echo $result = substr($myStr, 0, 10);
    echo "...</td>";
    echo "<td>".$row['tara']."</td>";
    echo "<td>".$row['oras']."</td>";
    echo "<td>".$row['isp']."</td>";
    echo "</tr>";
  }

  echo "</table>";

  /* Begin Navigation */ 

  echo "<table style='text-align: center; padding-left: 130px;'>";

  echo "<tr>";

  if ($page-1 >= 1) {
    echo "<td><a href=".$_SERVER['PHP_SELF']."?page=".($page - 1)."><Anterior</a></td>";
  }

  if ($page+1 <= $total_pages) {
    echo "<td><a href=".$_SERVER['PHP_SELF']."?page=".($page + 1).">Urmator ></a></td>";
  }

  echo "</tr>";

  echo "</table>";

  /* End Navigation */

} catch(PDOException $e) {
  echo $e->getMessage();
}

?>
Multumesc frumos, o zi buna tuturor!!!
„Uneori o greşeală poate fi tot ce este necesar pentru o realizare valoroasă.” — Henry Ford

MarPlo Mesaje: 4343
Salut,
La $sqlcount nu e nevoie sa adaugi ORDER BY.
Incearca al doilea sql asa:

Cod: Selectaţi tot

$sql = "select * from acasa ORDER BY id DESC limit :offset, :per_page";

MelecaCristian Mesaje: 176
Multumesc mult de ajutor, functioneza perfect!!!
„Uneori o greşeală poate fi tot ce este necesar pentru o realizare valoroasă.” — Henry Ford

Subiecte similare