2016-09-06 80 views
0

我遇到了一個問題。如果可能的話,我可以爲$ _GET ['topic']編寫一個else語句嗎?

case 'thread-view': 
     if(isset($_GET['topic'])){ 
     $topicid = $_GET['topic']; 

     $psql = "SELECT * FROM posts WHERE th_p_link='$topicid' ORDER BY p_id ASC"; 
     $presult = mysqli_query($db,$psql); 
     while($prow = mysqli_fetch_array($presult)){ 

      $post = $prow['p_post']; 
      $author = $prow['p_author']; 
      $avatar = $prow['p_avatar']; 
      $gm = $prow['p_gm']; 
      $date = $prow['p_date']; 
      $link = $prow['th_p_link']; 

     echo ' 
     <div class="post_box"> 
      <div id="post-left"> 
       <img src="'.$avatar.'" alt=""> 
       <div id="post-about"> 
        <span>'.$author.'</span> 
        <span>Member</span> 
       </div> 
      </div> 
      <div id="post-content"> 
      <p>'.htmlspecialchars($post, ENT_QUOTES).'</p> 
      </div> 
      <div id="post-right"> 
      <i>'.$date.'</i> 
      </div> 
     </div> 
     '; 
     } 
     } 
    break; 

    default: 
    include 'template/forum_categories.php'; 

舉個例子,如果我去的URL

forums.php?網頁=線程視圖&話題= testurlpost

它正確地顯示頁面。雖然我想要實現的是,如果我去的東西,不存在如

forums.php?網頁=線程視圖&話題= testurlthatdoesntexist

我想它重新導向到另一個頁面,例如錯誤頁面。我將如何實現這一目標?我爲$ _GET ['topic']做了一個else語句,但是當我輸入不存在的URL時,這不起作用。

+0

'/forums.php?topic =';%20DROP%20TABLE%20posts;%20 - ' – CD001

+0

是否有錯誤,這就是爲什麼它沒有工作?你有沒有檢查你的錯誤日誌? –

+0

查詢後,檢查結果行是否有零行,比id沒有存在,所以你可以使用'header('Location:xy.php'); exit;'重定向 – JustOnUnderMillions

回答

0

你應該在語句前加上

if(!mysqli_num_rows($presult)) { 
     header("Location: /error-page.html"); 
    } 

。所以,你的代碼將是這個樣子:

case 'thread-view': 
    if(isset($_GET['topic'])){ 
    $topicid = $_GET['topic']; 

    $psql = "SELECT * FROM posts WHERE th_p_link='$topicid' ORDER BY p_id ASC"; 
    $presult = mysqli_query($db,$psql); 

    if(!mysqli_num_rows($presult)) { 
     header("Location: /error-page.html"); 
    } 

    while($prow = mysqli_fetch_array($presult)){ 
+0

中的第一個單引號'\''謝謝!我完全忘記了mysqli_num_rows函數 – Synyster