PHP MySQL Order By
PHP mysql_query()函数用于执行带有order by子句的select查询。自PHP 5.5以来,mysql_query()函数已被弃用。现在推荐使用其中的两种替代方法。
- mysqli_query()
- PDO::__query()
order by子句用于根据列进行升序或降序获取数据。
让我们看一下在emp4表中根据name列升序选择数据的查询。
SELECT * FROM emp4 order by name
让我们看看根据名称列降序选择 emp4 表中的数据的查询。
SELECT * FROM emp4 order by name desc
PHP MySQLi 按照示例排序
示例
<?php
host = 'localhost:3306';user = '';
pass = '';dbname = 'test';
conn = mysqli_connect(host, user,pass,dbname);
if(!conn){
die('Could not connect: '.mysqli_connect_error());
}
echo 'Connected successfully<br/>';
sql = 'SELECT * FROM emp4 order by name';retval=mysqli_query(conn,sql);
if(mysqli_num_rows(retval)>0){ while(row = mysqli_fetch_assoc(retval)){ echo "EMP ID :{row['id']} <br> ".
"EMP NAME : {row['name']} <br> ". "EMP SALARY : {row['salary']} <br> ".
"--------------------------------<br>";
} //end of while
}else{
echo "0 results";
}
mysqli_close($conn);
?>
输出:
Connected successfully
EMP ID :3
EMP NAME : jai
EMP SALARY : 90000
--------------------------------
EMP ID :2
EMP NAME : karan
EMP SALARY : 40000
--------------------------------
EMP ID :1
EMP NAME : ratan
EMP SALARY : 9000
--------------------------------