Chapter 7: Improving the Dashboard
194
If you edit any of the products you processed, you ’ ll see that the category and grouping fields were
updated. In short order, you ’ ve addressed an important issue and made life for Claudia and her staffers
a lot easier. It ’ s time to move on to the import/export features.
Importing and Exporting
Importing and exporting data are crucial to any application ’ s success. They give the customer more
power and flexibility than you can provide with just a web application alone. Why? Because many
business applications are intimately tied to spreadsheets, and being able to accept data (and output data)
in CSV (comma - separated values) or TSV (tab - separated values) format can make life better for the user
along various dimensions. For example, if Claudia had to upload 100 products into her product
inventory one at a time, that would be very time - consuming. On the other hand, if she could export a
CSV file from Excel and then import that file, she might be able to get all 100 products into the system
with one pass, thus saving her a great deal of time and effort.
In this section, you first build an export function for Categories and then take what you ’ ve learned and
do the same thing for Products. Once all that is done, you will do the slightly harder work of importing
data from a spreadsheet into the Products table.
Creating an Export Function for Categories
In this example, you ’ re going to start with the model. Why? Because in CodeIgniter 1.6 and higher, you
have access to a very neat tool called dbutil. Its formal name is the Database Utility Class.
What does it do? It ’ s a class that helps you manage your database. The methods found in the class help
you list databases, optimize and repair tables, back up your database, and export in both CSV and XML
formats. It ’ s the ability to export in CSV format that you care about the most at the moment.
To invoke this class, simply call it:
$this- > load- > dbutil();
Once the class is loaded, you can then call the methods like this:
$this- > dbutil- > csv_from_result();
Now it ’ s time to create the exporter for categories. Open the MCats model and create an exportCsv()
function. The first thing you need to do in this function is load the Database Utility Class:
function exportCsv(){
$this- > load- > dbutil();
}
Once you have it loaded, create a simple query that selects all data from the categories table. Why not
just reuse one of the handy functions built in previous chapters (like getAllCategories() )? Well, you
really don ’ t need that much horsepower in this case — particularly as those other functions create neat
arrays that are ready for further processing.