0

嗨,在不再次执行查询的情况下从查询中进行“排序”的最佳方法是什么?假设当我必须使用表单查找姓名或姓氏时,我有一个搜索查询,例如:

     //Array for storing WHERE part of query
   $where=array();  

   if(!empty($name)) AND !empty($surname)){
         $where[]="Name LIKE '%$name%'" .
            "AND Surname LIKE '%$surname%'";
   }
   elseif(!empty($name)){
        $where[]="Name LIKE '%$name%'";
   }
   elseif(!empty($surname)){
       $where[]="Surname LIKE '%$surname%'";
   }

   $where = implode(' AND ', $where);

   $sql="SELECT Name,Surname FROM TABLE WHERE $where ORDER BY Name DESC";

   $res = mysql_query($sql);

   while ($row = mysql_fetch_array($res, MYSQL_NUM)) {
           $name    = $row[0];
           $surname    = $row[1];
           echo"$name";
           echo"$surname";


    }

如何在搜索“Name LIKE %surname%”后以 ASC 模式(ORDER BY Name ASC)显示姓名或姓氏,而无需再次执行 SQL 查询?例如,当我搜索包含“ich”字的名称时,我想以这种方式列出一个列表:

  MICHAEL
  PICHAEL
  XICHAEL
    => the ASC mode
  XICHAEL
  PICHAEL
  MICHAEL
   => the DESC mode
4

2 回答 2

0

你说的是像这样颠倒数组的顺序吗?

<?php

  //Array for storing WHERE part of query
   $where=array();  

   if(!empty($name) && !empty($surname)){
         $where[]="Name LIKE '%$name%'" .
            "AND Surname LIKE '%$surname%'";
   }
   elseif(!empty($name)){
        $where[]="Name LIKE '%$name%'";
   }
   elseif(!empty($surname)){
       $where[]="Surname LIKE '%$surname%'";
   }

   $where = implode(' AND ', $where);

   $sql="SELECT Name,Surname FROM TABLE WHERE $where ORDER BY Name";

   $res = mysql_query($sql);

    $names = array();
    $surnames = array();
    $wholeNames = array();

    $x='0';
   while ($row = mysql_fetch_array($res)) {

           if(!empty($row['Name'])){
                $names[$x] = $row['Name'];
           }
           if(!empty($row['Surname'])){
                $surnames[$x] = $row['Surname'];
           }

           if(!empty($row['Name'])&&!empty($row['Surname'])){
             $wholeNames[$x] = $row['Name'].' '.$row['Surname'];
           }
          $x++; 
    }
print "<pre>\n";
print_r ($names);
print_r ($surnames);
print_r ($wholeNames);
print "</pre>\n";

$reversed_names=array_reverse($names);
$reversed_surnames=array_reverse($surnames);
$reversed_wholeNames=array_reverse($wholeNames);

print "<pre>\n";
print_r ($reversed_names);
print_r ($reversed_surnames);
print_r ($reversed_wholeNames);
print "</pre>\n";


?>

需要注意的一点是,如果您将 LIKE 与通配符一起使用,则搜索“Art”将匹配 Bart、Arthur、carter 以及其中包含“Art”的任何其他单词。

于 2013-03-26T00:32:24.420 回答
0

我真的不认为我正确理解了您的问题,但是我要在这里冒险并猜测您只想按两个不同的列排序?

 $sql="SELECT Name,Surname FROM TABLE WHERE $where ORDER BY Name DESC, Surname ASC";

"顺便说一句,您的查询字符串中有一个额外的

此外,您可能想研究使用mysql_fetch_assoc而不是mysql_fetch_array

这只是我现在在挑剔......但不是使用:

    echo"$name";
    echo"$surname";

你可以写:

echo $name;
echo $surname;
于 2013-03-25T23:44:28.847 回答