0

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";
    }
?>
Machavity
  • 30,841
  • 27
  • 92
  • 100
Jenny
  • 1
  • 2
  • 1
    Please don't change the question completely, instead update the question and specify what changes you have made in the code(and related side-effects/further requirements), otherwise it would confuse future readers of SO. – Rajdeep Paul Jan 09 '17 at 16:13

1 Answers1

2

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

Community
  • 1
  • 1
Rajdeep Paul
  • 16,887
  • 3
  • 18
  • 37
  • Hi @Rajdeep let me know what you think to the update thanks – Jenny Jan 08 '17 at 21:08
  • @Jenny Good to see that you've switched to `MySQLi`, but your query is still susceptible to SQL injection attacks. Use prepared statement, as specified in my answer also. Start with this, [http://php.net/manual/en/mysqli.quickstart.prepared-statements.php](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) – Rajdeep Paul Jan 09 '17 at 16:16