Jenny
Jenny

Reputation: 1

Why is ORDER BY id DESC not working in this line?

I'm trying to get ORDER BY id DESC to work in this line of php but I can't get it to work. It works without it though but they just display in the opposite order. Where should I position it?

$query = mysql_query("SELECT * FROM photos ORDER BY id DESC WHERE title LIKE '%".$search."%'");

Update: I've updated the php with your suggestion that works now thanks. I've also updated it to mysqli as suggested, could this be structured better in anyway? It is working, just wondered if anyone has any improvements?

<?php
    $search = $_GET['search'];
    $db = mysqli_connect("", "", "", "") or die ("could not connect to mysql");
    $sql = "SELECT * FROM photos WHERE title LIKE '%".$search."%' ORDER BY id DESC";
    $result = mysqli_query($db, $sql);
    if(mysqli_num_rows($result) >=1) {
        while ($row = mysqli_fetch_array($result)) {
            echo"<div id='img_div'>";
                echo"<img src='images/".$row['image']."'>";
                echo"<h1>".$row['title']."</h1>";
                echo"<p>".$date = date('j F, Y', strtotime($row['date']))."</p>";
                echo"<p>".$row['link']."</p>";
            echo"</div>";    
        }
        //continue
    }else{
        echo "No Results";
    }
?>

Upvotes: 0

Views: 1618

Answers (1)

Rajdeep Paul
Rajdeep Paul

Reputation: 16963

Your query is wrong. ORDER BY id DESC should be placed after the WHERE clause, like this:

$query = mysql_query("SELECT * FROM photos WHERE title LIKE '%".$search."%' ORDER BY id DESC");

Sidenote(s):

Upvotes: 2

Related Questions