0

I am trying to get the parameter from my URL. This is how it looks http://localhost/project1/post.php?subtopic_id=3. This is how I get the parameter from the URL

$subtopic_id = isset($_GET['subtopic_id']) ? $_GET['subtopic_id'] : 3 ;

When I put a number in the else statement (like I currently have the number 3 in it) I get that number. But when I have the else statement blank the only number that shows up in the DB is 0. I don't know why this is happening even though the parameter in the URL has a value in it.

When the code is like this and I try to add a comment to my post the subtopic_id value is 0 when it's suppose to have a different number

$subtopic_id = isset($_GET['subtopic_id']) ? $_GET['subtopic_id'] : '' ;
Barmar
  • 741,623
  • 53
  • 500
  • 612
user13477176
  • 119
  • 6
  • 1
    Not related to your problem, but this pattern was so common that it was given a special syntax in PHP 7.0 called the [null coalescing operator](https://www.php.net/manual/en/migration70.new-features.php#migration70.new-features.null-coalesce-op). You can instead write `$subtopic_id = $_GET['subtopic_id'] ?? 3;` – Chris Haas Jul 20 '21 at 20:45

1 Answers1

1

It's a common pitfall.

I guess you're using a common form with subtopic_id being one input? Even when the input is empty, it will be send. Therefore you should not only check whether the variable is set but also if the variable is empty:

$subtopic_id = !empty($_GET['subtopic_id']) ? $_GET['subtopic_id'] : 3 ;
maio290
  • 6,440
  • 1
  • 21
  • 38
  • That didn't work either. Still gives the value of `0` – user13477176 Jul 20 '21 at 20:40
  • @user13477176 Depending on what you are doing with that variable, you may have to parse it into an integer first. $_GET parameters by default are String values. – maio290 Jul 20 '21 at 20:41
  • But it works in another project just fine. How would I do that ? – user13477176 Jul 20 '21 at 20:43
  • @user13477176 [click me!](https://stackoverflow.com/a/8529687/4934937) - other than that, there is no way we can figure out the error with the little amount of information given. – maio290 Jul 21 '21 at 02:20