Chapter 6: Creating a Dashboard
163
redirect(‘admin/categories/index’,’refresh’);
}else{
$data[‘title’] = “Create Category”;
$data[‘main’] = ‘admin_cat_create’;
$data[‘categories’] = $this- > MCats- > getTopCategories();
$this- > load- > vars($data);
$this- > load- > view(‘dashboard’);
}
}
OK, now it ’ s time to create your two new functions in your model. The easiest one to deal with at the
moment is the getTopCategories() function. Basically, you want to end up with an array that contains
the topmost category (category 0, which represents the root of the category tree) and every category
whose parentid is equal to 0.
function getTopCategories(){
$data[0] = ‘root’;
$this- > db- > where(‘parentid’,0);
$Q = $this- > db- > get(‘categories’);
if ($Q- > num_rows() > 0){
foreach ($Q- > result_array() as $row){
$data[$row[‘id’]] = $row[‘name’];
}
}
$Q- > free_result();
return $data;
}
The second function, addCategory() , is much more straightforward. All you have to do to add data to
a table is load up a data array and then pass that array to $this- > db- > insert() along with a table
name. Presto, your information is inserted.
Don ’ t worry about database security at the moment. You ’ ll be doing a pass in Chapter 9 that will take
care of most of the problems you might encounter.
function addCategory(){
$data = array(
‘name’ = > $_POST[‘name’],
‘shortdesc’ = > $_POST[‘shortdesc’],
‘longdesc’ = > $_POST[‘longdesc’],
‘status’ = > $_POST[‘status’],
‘parentid’ = > $_POST[‘parentid’]
);
$this- > db- > insert(‘categories’, $data);
}
A quick note here about security and validation. Normally, at this point, you would run each of these
fields from the form through a validation process (to make sure they are the right length or hold the right
data). In Chapter 9 , you learn how to implement different methods for cleaning up this kind of user
input. For now, with XSS Global Filtering turned on, you should rest easy enough.