如何在表上对SQL的结果进行排序

时间:2017-06-16 12:24:48

标签: php sql sql-server

我希望从MSSQL表中排序结果,但需要使用会话..我的代码类似于'?sort = id'但是我想要每次会议,任何人都可以帮助我吗?

                <?php   
                $ordenarpor = isset($_GET['ordena']) ? $_GET['ordena'] : 'id';
                $ordenar = '';
                if ($ordenarpor== 'id')
                {
                    $ordenar .= " ORDER BY id";
                }
                elseif ($ordenarpor== 'nome')
                {
                    $ordenar .= " ORDER BY nome";
                }
                elseif ($ordenarpor== 'idade')
                {
                    $ordenar .= " ORDER BY idade";
                }
                elseif($ordenarpor== 'peso')
                {
                    $ordenar .= " ORDER BY peso";
                }   
            $nomeServidor = "fsadaxa-DEMO"; 
            $opcao = array(  "UID" => "sa",  "PWD" => "sadasx",  "Database" => "demo");
            $conexao = sqlsrv_connect($nomeServidor, $opcao);
                if( $conexao ) {
                $sql="SELECT * FROM cliente" . $ordenar;
                $aResult=sqlsrv_query($conexao, $sql);
                while($rows = sqlsrv_fetch_array($aResult))
                { 
                $id = $rows['id'];
                $nome = $rows['nome'];
                $idade = $rows['idade'];
                $peso = $rows['peso'];

                    ?>

目前这是我的代码,但我想按会话进行

1 个答案:

答案 0 :(得分:0)

设置新的$_SESSION变量时,请使用以下代码设置$_GET变量 如果未设置$_GET变量,请改用$_SESSION变量 如果两者都未设置,请使用默认值:'id'

$ordernarpor = 'id';
if(isset($_GET['orderna']))
{
    $ordernarpor = $_GET['orderna'];
    $_SESSION['orderna'] = $ordernarpor;
}
else if(isset($_SESSION['orderna']))
{
    $ordernarpor = $_SESSION['orderna'];
}
$ordenar = '';
if ($ordenarpor== 'id')
{
    $ordenar .= " ORDER BY id";
}
elseif ($ordenarpor== 'nome')
{
    $ordenar .= " ORDER BY nome";
}
elseif ($ordenarpor== 'idade')
{
    $ordenar .= " ORDER BY idade";
}
elseif($ordenarpor== 'peso')
{
    $ordenar .= " ORDER BY peso";
}   
$nomeServidor = "fsadaxa-DEMO"; 
$opcao = array(  "UID" => "sa",  "PWD" => "sadasx",  "Database" => "demo");
$conexao = sqlsrv_connect($nomeServidor, $opcao);
if( $conexao ) {
$sql="SELECT * FROM cliente" . $ordenar;
$aResult=sqlsrv_query($conexao, $sql);
while($rows = sqlsrv_fetch_array($aResult))
{ 
    $id = $rows['id'];
    $nome = $rows['nome'];
    $idade = $rows['idade'];
    $peso = $rows['peso'];