为什么ORDER BY ID DESC无法在此行中运行?

时间:2017-01-08 18:41:46

标签: php mysql sql-order-by

我试图让ORDER BY id DESC在这行php中工作,但我无法让它工作。它虽然没有它,但它们只是以相反的顺序显示。我应该在哪里定位?

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

更新 我已经用您的建议更新了PHP,现在可以使用了。我也按照建议将它更新为mysqli,无论如何这可以更好地构建吗?它工作正常,只是想知道是否有人有任何改进?

<?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";
    }
?>

1 个答案:

答案 0 :(得分:3)

您的查询错误。 ORDER BY id DESC应放在 WHERE子句之后,如下所示:

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

旁注: