Peter Atanasov
Peter Atanasov

Reputation: 79

Why are the images on my website still displayed in ascending order by id even though I am using order by id desc?

I ran the query on my database and it returned the correct descending order, however, on my website the images are still displayed in ascending order. I want the images with higher ID to be displayed on top of the page.

<?php
    $sql = "SELECT * FROM image ORDER BY id DESC";
    $result = mysqli_query($conn, $sql);

    while ($row = mysqli_fetch_array($result)) {
        echo "<div class='imageContainer'>"
            ."<h1>".$row["name"].'</h1>'
            .'<a href="imageInfo.php?image='.$row["path"].'"><img class="uploadedImg" src="uploads/'.$row["path"] .'" alt="Random image" /></a>
            </div>'; 
    }
?>

Upvotes: 1

Views: 48

Answers (1)

Shashikant Chauhan
Shashikant Chauhan

Reputation: 444

Here is solution. it is working in my system. please have a look and let me know.if any more errors comes. In this i used object of database connection. and method i used $result->fetch_assoc(). Here is link for more info on this method : http://php.net/manual/en/mysqli-result.fetch-assoc.php

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT * FROM image ORDER BY id DESC";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        // echo "<div class='imageContainer'><h1>".$row["name"]."'</h1><a href="imageInfo.php?image='.$row["path"].'"><img class="uploadedImg" src="uploads/'.$row["path"] .'" alt="Random image" /></a></div>";
        echo "<div class='imageContainer'>"
            ."<h1>".$row["name"].'</h1>'
            .'<a href="imageInfo.php?image='.$row["path"].'"><img class="uploadedImg" src="uploads/'.$row["path"] .'" alt="Random image" /></a>
            </div>'; 

    }
} else {
    echo "0 results";
}
$conn->close();
?>

Upvotes: 1

Related Questions