Get 및 Post 변수를 모두 사용하여 정렬 및 검색을 수행하려면 어떻게해야합니까?

StackOverflow https://stackoverflow.com/questions/1814544

문제

현재 Column Header 's As as as asks를 링크하고 있습니다. 클릭하면 URL에 get 변수를 추가하여 열 이름별로 결과를 정렬 할 것입니다. 예는 다음과 같습니다.

<a href="
  <?php
  // Sorts by order id. If already sorted by order id, then it will change the link to sort descending
  if(!isset($_GET['sortby']) || $_GET['sortby'] != 'order_id'){
    echo $_SERVER['SCRIPT_NAME'] . '?sortby=order_id';  //example: tracker.php?sortby=order_id
  } elseif(isset($_GET['sortby']) || $_GET['sortby'] == 'order_id'){
    echo $_SERVER['SCRIPT_NAME'] . '?sortby=order_id_desc'; //example: tracker.php?sortby=order_id_desc
  }?>
">Order ID</a>

또한 사용자가 SelectBox에서 카테고리를 선택한 다음 검색기를 입력 할 수있는 양식도 있습니다. $ _get [ 'sortby'] 변수와 $ _post [ 'search_submit'] 변수가 설정되어 있는지 확인하기 위해 If 문과 스위치 명령문을 사용하고 있습니다. .

4 가지 시나리오가 있습니다.

1. 기본값 : 정렬이나 검색이 설정되지 않은 경우. 이것은 잘 작동합니다.

if(!isset($_GET['sortby']) && !isset($_POST['search_submit'])){ //Default, If no sort or search is set
  $sql = 'SELECT * 
          FROM orders 
          ORDER BY order_id DESC'; 
}

2. 검색이 설정되어 있지만 정렬이 그렇지 않은 경우. 이것은 잘 작동합니다.

if(isset($_POST['search_submit'])) {
  $search_string = ' WHERE ' . $_POST['searchby'] . '= "' . $_POST['search_input'] . '" ';
}

if(!isset($_GET['sortby']) && isset($_POST['search_submit']) ){ //If the search is set but no sort
  $sql = "SELECT * 
          FROM orders"
          . $search_string . 
          "ORDER BY order_id DESC";
}

3. 정렬이 설정되어 있지만 검색은. 이것은 잘 작동합니다.

if(isset($_GET['sortby']) && !isset($_POST['search_submit'])) { //If the sort is set but no search
  switch ($_GET['sortby']) { 
    case "order_id":
      $sql = "SELECT * 
              FROM orders 
              ORDER BY order_id ASC";
    break;

    case "order_id_desc":
      $sql = "SELECT * 
              FROM orders  
              ORDER BY order_id DESC";
    break;
  }
}

4. 검색 및 정렬이 설정된 경우. 위의 3 가지가 모두 작동하지만 마지막 진술은 나에게 문제를 일으킨다.

if(isset($_GET['sortby']) && isset($_POST['search_submit'])) { //If the sort AND search is set
  switch ($_GET['sortby']) { 
    case "order_id":
      $sql = "SELECT * 
              FROM orders"
              . $search_string . 
              "ORDER BY order_id ASC";
    break;

    case "order_id_desc":
      $sql = "SELECT * 
              FROM orders"
              . $search_string . 
              "ORDER BY order_id DESC";
    break; 
  }
} 

어떤 일이 발생하는지 검색 할 수는 있지만 열 헤더 중 하나를 클릭하면 새 Get Variable을 사용하여 페이지를 다시로드하자마자 현재 게시물 변수를 제거하여 모든 결과를 다시 표시합니다. $ _post [ 'search_submit'] isset 이후 현재 게시물 변수를 세션에로드하려고 시도한 다음 마지막 if 문을 확인하여 세션 변수가 설정되어 있는지 확인했지만 세션이 항상 설정되고 세션이 설정되어 있습니다. 홈페이지로 돌아 가려고하면 해당 검색 결과가 유지됩니다.

어딘가에 세션을 파괴해야할까요? 아마도 정렬과 검색 기능을 결합하는 데 취할 수있는 전반적인 더 나은 접근 방식이 있을까요?

도움이 되었습니까?

해결책

검색 양식을 a에서 변경하는 것이 좋습니다 method="POST" 에게 method="GET" 그리고 모든 요청을 위해 사용하십시오. 게시물 요청을 변경할 수없는 경우 각 요청 (정렬 포함)을 게시해야합니다.이 요청은 정렬 링크에 첨부 된 JavaScript가 필요합니다.

Get을 사용하는 이점은 모든 데이터가 쿼리 문자열에 포함되므로 사용자가 특정 검색을 북마크 할 수 있다는 것입니다.

편집하다: 후속 요청에서 검색 문자열을 유지합니다.

나는 당신의 정렬 코드를 다음과 같은 것으로 추상화 할 것입니다.

<?php
function write_sortable_header_link( $column_id, $column_name ){
   if( ( isset($_GET['sortby']) && $_GET['sortby'] != $column_id ) || !isset($_GET['sortby']) )
     $query = "?sortby=$column_id";
   else
     $query = '?sortby='.$column_id.'_desc';

   if( isset($_GET['searchsubmit']) ){
     $query .= '&amp;searchsubmit=1';
     $query .= '&amp;searchby=' . urlencode( isset($_GET['searchby']) ? $_GET['searchby'] : '' );
     $query .= '&amp;search_input=' . urlencode( isset($_GET['search_input']) ? $_GET['search_input'] : '' );
   }

   $href = $_SERVER['SCRIPT_NAME'] . $query;
   echo "<a href='$href'>$column_name</a>";
}
?>

그런 다음 다음과 같이 부릅니다.

<?php write_sortable_header_link( 'order_id', 'Order Id' ); ?>

정렬 URL에 지속성에 대한 올바른 쿼리 문자열 인수가 포함되어 있는지 확인합니다.

다른 팁

사용하려고 노력하십시오 $_GET 만 포함합니다 $_POST 불필요한 것 같습니다.

당신의 질문에 대한 답이 아니라 내 0.2

귀하의 상황에서 나는 일반적으로 JavaScript를 사용하여 웹 브라우저에서 정렬 클라이언트 측을 수행합니다. 파라미터별로 다른 순서만으로 동일한 쿼리가 계속해서 계속 실행되는 것을 방지합니다.

jQuery에는 매우 쉬운 플러그인도 있습니다.

예시: http://tablestertor.com/docs/

이것은 DCNEINER에서 제안한대로 정렬 및 검색 get 변수로 링크를 다시 작성하기 위해 사용한 코드입니다. 나는 Urlencode, Switched & '&'부호를 꺼내고 진술이 get 변수를 설정할 수있는 유일한 방법은 search_submit가 일부로 설정되어 있으므로 설정 될 수있는 유일한 방법은 Get 변수로 표시되면 인라인을 만들었습니다. 같은 형태. 또한 '{'및 '}'를 IF와 Else 문에 다시 추가했습니다. PHP를 수행하는 약간 다른 방법을 사용하고 있다고 생각하십니까? 내가 만든 변화에 대해 잘못되었거나 안전하지 않습니까? 나는 당신이 왜 당신의 길을했는지 너무 확신하지 못했습니다. 그러나 다시 한 번 감사드립니다.

function write_sortable_header_link( $column_id, $column_name ){ //Function that creates a link with the search query if needed
  if( ($_GET['sortby'] != $column_id) || !isset($_GET['sortby']) ) { //If the GET variable is not the column id of this button or if the GET sortby variable has not been set
    $query = "?sortby=$column_id"; //then add this to the end of the url
  } else {
      $query = '?sortby='.$column_id.'_desc'; //otherwise if the GET variable is the column id of this button, then add the descending code to the end of the variable
  }

  if(isset($_GET['search_submit']) ){ //If the GET variable search_submit is in the url
    $query .= '&search_submit=1'; //then add this to the end of the url string
    $query .= '&searchby=' . $_GET['searchby']; //add whatever is currently in the GET searchby to the end of the url string
    $query .= '&search_input=' . $_GET['search_input']; //add whatever is currently in the GET search_input to the end of the url string
  }

  $href = $_SERVER['SCRIPT_NAME'] . $query; //this is the href part of the link
  echo "<a href='$href'>$column_name</a>"; //this creates the actual link
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top