Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialArash Emadi
10,002 PointsHow can I prevent access to my view if there's not an article with that ID in CodeIgniter?
Hi. I'm developing a web app on CodeIgniter.
When the users want to view an article on my website, they will go to a URL like articles/view/2 . Now I just found out that if someone just randomly passes in a number like 255 it won't go to 404 and it will show an error instead. How can I fix this? How can I say, if it's not a valid article ID, redirect them or smth like that? Thanks in advance.
1 Answer
miguelcastro2
Courses Plus Student 6,573 PointsThe issue here is that you have a URL that uses a primary key to retrieve a record from the database. If the record does not exist, your app crashes. You always need to check to see if the database successfully retrieved a record. You need to add code to check whether your model was able to retrieve a record and if not, use CodeIgniters show_error() function to display an error. Below is a pseudo code sample:
<?php
// Get ID from URL
$id = 255;
if ($this->myModel->find($id)) {
// Load Views
} else {
show_error("Error: could not locate articles.");
}
?>
A Better way would be to use PHP exceptions to generate an exception when a record is not found and use try/catch to respond to the exception.
The overall idea is that as a developer you need to make sure your program is prepared to handle different scenarios, especially the ones where you do not receive the input you were expecting.