So I have this method inside one of my Controllers that I use to edit content:
public function edit($id){
$data;//some data that i gather
$this->load->view('admin/layouts/main',$data);
}
}
And well I can redirect if $id
is empty, and display a message, something like this:
public function edit($id){
if(empty($id)){
redirect('admin/articles');
//here some session variable to store message that i display later
}
$data;//some data that i gather
$this->load->view('admin/layouts/main',$data);
}
And for example if I will try to access my method like this: host.com/controller/method/id
and if id
will be empty it will redirect me.
But how do i check if id
that I pass is correct, and there is a real article in my database, that has corresponding id
and can be edited?
P.S. I use CodeIgniter as a framework.
You can do something like this,
public function edit($id = 0){
// setting $id zero if not passed
// check $id is integer and > 0
ctype_digit($id) or redirect('admin/articles');
// check record exists in your table
$result = $this->db->get_where('table', array('id' => $id));
// $result will be false if no record found
$result or redirect('admin/articles');
$data = array();
// if you need that in view
$data['id'] = $id;
$data['result'] = $result;
$this->load->view('admin/layouts/main',$data);
}
For the id you can always use the is_integer function. And for the article, all you can do is trying to get the article by it's id and redirecting if you don't find any.
After you validate the contents of the id
(i.e. is a numeric one), you need to query the database by that id
. If the query returns nothing, it means the id
is not in the database, and you can redirect to the articles
page.