嗨,从查询中执行'order by'而不执行另一次查询的最佳方法是什么?假设我有一个搜索查询,当我必须使用表单找到名字或姓氏时,例如:
//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
答案 0 :(得分: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;
答案 1 :(得分:0)
Arr你在谈论像这样颠倒数组的顺序吗?
<?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";
?>
需要注意的是,如果你使用喜欢通配符,那么搜索“艺术”会匹配Bart,Arthur,Carter以及任何其他包含“Art”的单词。