Synyster Synyster - 2 months ago 6
PHP Question

switch $_GET variable else statement

I've runned into a problem. If it's possible, can i write an else statement for the $_GET['topic'] ?

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';


For an example, if i go to the URL


forums.php?page=thread-view&topic=testurlpost


It shows the page correctly. Though what i'm trying to achieve is that if i go to something that doesn't exist such as


forums.php?page=thread-view&topic=testurlthatdoesntexist


I want it to re-direct to another page, such as an error page. How would i achieve this? I made an else statement for the $_GET['topic'] but that did not work when i entered the non-existing URL.

Answer

You should add

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

before While statement. So your code will look something like this:

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)){
Comments