我在哪里将ORDER BY放在这段代码中?

时间:2014-03-18 17:54:44

标签: php mysql mysqli

这是一个简单的问题,但我似乎无法弄明白。所以我有这个代码解析搜索并对结果进行分页。效果很好。

<?php
require_once("models/config.php");
if (!securePage($_SERVER['PHP_SELF'])){die();}
require_once("models/header.php");
define("NUMBER_PER_PAGE", 5); //number of records per page of the search results

function pagination($current_page_number, $total_records_found, $query_string = null)
{
    $page = 1;

    echo "Page: ";

    for ($total_pages = ($total_records_found/NUMBER_PER_PAGE); $total_pages > 0;     $total_pages--)
{
    if ($page != $current_page_number)
        echo "<a href=\"?page=$page" . (($query_string) ? "&$query_string" : "") .     "\">";

    echo "$page ";

    if ($page != $current_page_number)
        echo "</a>";

    $page++;
}
}

$page = ($_GET['page']) ? $_GET['page'] : 1;
$start = ($page-1) * NUMBER_PER_PAGE;


$personid = ($_POST['personid']) ? $_POST['personid'] : $_GET['personid'];
$firstname = ($_POST['firstname']) ? $_POST['firstname'] : $_GET['firstname'];
$surname = ($_POST['surname']) ? $_POST['surname'] : $_GET['surname'];

$sql = "SELECT * FROM persons WHERE 1=1";

if ($personid)
$sql .= " AND personid='" . mysqli_real_escape_string($mysqli,$personid) . "'";

if ($firstname)
$sql .= " AND firstname='" . mysqli_real_escape_string($mysqli,$firstname) . "'";

if ($surname)
$sql .= " AND surname='" . mysqli_real_escape_string($mysqli,$surname) . "'";


$total_records = mysqli_num_rows(mysqli_query($mysqli,$sql));


$sql .= " LIMIT $start, " . NUMBER_PER_PAGE;

pagination($page, $total_records,    "personid=$personid&firstname=$firstname&surname=$surname");



 $loop = mysqli_query($mysqli,$sql)
 or die ('cannot run the query because: ' . mysqli_error($mysqli,i));

 while ($record = mysqli_fetch_assoc($loop))
 echo "<br/>{$record['personid']}) " . stripslashes($record['firstname']) . " - {$record['surname']}";


 echo "<center>" . number_format($total_records) . " search results found</center>";

pagination($page, $total_records,     "personid=$personid&firstname=$firstname&surname=$surname");

&GT;

但是,我希望我的搜索结果按姓氏排序。所以我修改了一行代码来说明这一点:

$sql = "SELECT * FROM persons WHERE 1=1 ORDER BY surname";

然后当我搜索一个名字时,我得到了所有的记录,完全按姓氏排序。我曾尝试将ORDER BY放在其他地方,但搜索不起作用。

为了获得按姓氏排序的正确过滤结果,ORDER BY条件必须在这里进行吗?

提前感谢您的帮助。

4 个答案:

答案 0 :(得分:2)

你在找这样的东西吗?

$sql .= " ORDER BY surname";
$sql .= " LIMIT $start, " . NUMBER_PER_PAGE;

问题只是您需要在正在构建的SQL查询末尾附加“ORDER BY”语句吗?

答案 1 :(得分:1)

在此$sql .= " LIMIT $start, " . NUMBER_PER_PAGE;

之前添加订单
$sql .= " ORDER BY surname";
$sql .= " LIMIT $start, " . NUMBER_PER_PAGE;

答案 2 :(得分:0)

您的代码有什么问题?它返回记录结果无序或产生错误? ORDER BY的位置是正确的,所以可能在sql查询上有错误

一点建议,标签<center>在html5中已弃用,请使用css

答案 3 :(得分:-1)

尝试:

$sql = "SELECT * FROM persons WHERE 1=1 ORDER BY surname DESC";

或:

$sql = "SELECT * FROM persons WHERE 1=1 ORDER BY surname ASC";