Search code examples
phpurl-routing

PHP isset equal $var1 or $var2


I'm trying to make routing system.

What I want to do:

Url: http://localhost/wiki.php?post_id=1 invoke second if

Url's: http://localhost/wiki.php?post_id=1&action=upvote http://localhost/wiki.php?post_id=1&action=downvote invoke first if

This is routing system:

if(isset($_GET['post_id']) & ((isset($_GET['action']) ? $_GET['action'] : null) == "upvote" || "downvote")){
    //Do stuff
}else if(isset($_GET['post_id'])){
    //Do stuff
}

Problem:

Url's: http://localhost/wiki.php?post_id=1&action=upvote http://localhost/wiki.php?post_id=1&action=downvote work like they are supposed to.

But url: http://localhost/wiki.php?post_id=1 invokes first not second if too...

Notice: Undefined index: action in D:\xampp\htdocs\controllers\WikiController.php on line 18

Line 18: $rate = $_GET['action']; it's inside in first if.

While testing I figured out that if I change if(isset($_GET['post_id']) & ((isset($_GET['action']) ? $_GET['action'] : null) == "upvote" || "downvote")){

too

 if(isset($_GET['post_id']) & ((isset($_GET['action']) ? $_GET['action'] : null) == "upvote")){

or

 if(isset($_GET['post_id']) & ((isset($_GET['action']) ? $_GET['action'] : null) == "downvote")){

It works fine. But I want to learn how to do this right, not just simply made 2 different routers.


Solution

  • this part (exp) == "upvote" || "downvote" does not work like you suppose it does. It only tests if exp is equal to "upvote", the second part "downvote" is understood as a boolean which is true, so you stay in the first part of the alternative..

    try with

    if(isset($_GET['post_id']) && (($exp = (isset($_GET['action']) ? $_GET['action'] : null)) == "upvote" || $exp == "downvote")){