Suppose using a isset() function, we checked whether an ID did exist or the user did submit an ID, before assigning it to variables or using it some place in the code that follows.
<?php
if(isset($_GET['Id']))
{
$Id=$_GET['Id'];
}
?>
Now I understand, it’s good to do this
1)So the code as per the expected behavior i.e. does what it’s expected to accomplish. For Example – if id was going to be used in some query which would return a row based on that id, it’s always a good idea to provide a valid id to be sure that the query indeed returns a row as a result… This avoids the unexpected behavior that the query fails if it wasn’t provided with a valid id.
2)And as obvious, minimizing any runtime errors that our code might generate.
So, I’m looking for more relevant examples and context as to why this is always a good programming practise.
Basically more examples to help me sink in my understanding why it’s really good to do so … Many Thanks.
Think about the future.
If you simply stated
$id = $_GET['id']and used the variable later on, your application may behave in an unexpected manner.Say next week you come back and write some code that uses that convinenent
$idvariable. From glancing up in the file you see it used elsewhere and don’t plan on it not being set. That code works when you test it quickly, but fails under real-world use. Maybe it errors out, maybe it spits out an admin page, maybe it explodes and kills puppies, who knows?If you’d been a bit more careful, and done something like:
Your code would always have an
$idto work with. Note the small addition there, I haven’t simply ensured that$_GET['id']exists before I assign it’s value to another variable, I’ve ensured that$id/always/ has a value.If I was an ounce smarter, I’d probably do something like this instead:
if (isset($_GET['id'] && ctype_digit($_GET['id']) && isValidId($_GET['id']))