$this->form_validation->set_rules('email_confirm',
'Comfirmation Email Address',
'required|min_length[1]|max_length[255]|
valid_email|matches[email]');
$this->form_validation->set_rules(
'payment_address', 'Payment Address',
'required|min_length[1]|max_length[1000]');
$this->form_validation->set_rules(
'delivery_address', 'Delivery Address',
'min_length[1]|max_length[1000]');
// Begin validation
if ($this->form_validation->run() == FALSE) {
$this->load->view('shop/user_details');
} else {
$cust_data = array(
'cust_first_name' =>
$this->input->post('cust_first_name'),
'cust_last_name' =>
$this->input->post('cust_last_name'),
'cust_email'=>
$this->input->post('cust_email'),
'cust_address' =>
$this->input->post('payment_address'),
'cust_created_at' => time());
$payment_code = mt_rand();
$order_data = array(
'order_details' => serialize(
$this->cart->contents()),
'order_delivery_address' =>
$this->input->post('delivery_address'),
'order_created_at' => time(),
'order_closed' => '0',
'order_fulfilment_code' => $payment_code,
'order_delivery_address' =>
$this->input->post('payment_address'));
if ($this->Shop_model->save_cart_to_database(
$cust_data, $order_data)) {
echo 'Order and Customer saved to DB';
} else {
echo 'Could not save to DB';
}
}
}
}
65
Creating E-commerce Features
4. Add public function save_cart_to_db() to the models/shop_model.php model as follows:
public function save_cart_to_database(
$cust_data, $order_data) {
$this->db->insert('customer', $cust_data);
$order_data['cust_id'] = $this->db->insert_id();
if ($this->db->insert('orders', $order_data)) {
return true;
} else {
return false;
}
}
5. Amend the, views/shop/display_cart.php file. At the top of the page, add the following line:
<?php echo anchor('cust/user_details',
'Proceed to checkout') ; ?>
6. Create the filepath/to/codeigniter/application/views/shop/
user_details.php file and add the following code into it:
<body>
<?php echo validation_errors(); ?>
<?php echo form_open('/cust/user_details') ; ?>
<?php echo form_input(array('name' => 'first_name',
'value' => 'First Name', 'maxlength' => '125',
'size' => '50')); ?><br />
<?php echo form_input(array('name' => 'last_name',
'value' => 'Last Name', 'maxlength' => '125',
'size' => '50')); ?><br />
<?php echo form_input(array('name' => 'email',
'value' => 'Email Address', 'maxlength' => '255',
'size' => '50')); ?><br />
<?php echo form_input(array('name' =>
'email_confirm', 'value' => 'Confirm Email',
'maxlength' => '255', 'size' => '50')); ?>
<br />
<?php echo form_textarea(array('name' =>
'payment_address', 'value' => 'Payment Address',
'rows' => '6', 'cols' => '40',
'size' => '50')); ?><br />
<?php echo form_submit('', 'Enter') ; ?><br />
<?php echo form_close() ; ?>
</form>
</body>
66
Chapter 3
How it works...
To explain what's happening here, let's look at this from the customer's perspective.
The customer has taken a look around the store and has selected a few items and placed them into the cart. The next step is to convert that cart into an order. So, the user clicks on View Cart to view the products they wish to order (we've already covered this, so we won't go into it again.) When the user clicks on Proceed to checkout, the public function, user_details(), is called, which displays views/shop/user_details.php to the customer. This asks them to enter some information; in this case, their name, e-mail address, payment, delivery address, and so on. On successfully submitting the form (that is, no validation errors), their order is moved from the cart to the database and matched with their submitted user details.
A tracking code is also created with the line, $payment_code = mt_rand(), which can be used to track the payment through a payment providers system.
67
4
Email, HTML Table,
and Text Libraries
In this chapter, you will learn:
f
Sending plain e-mails with CodeIgniter Email
f
Sending HTML e-mails with CodeIgniter Email
f
Sending attachments with CodeIgniter Email
f
Sending bulk e-mails with CodeIgniter Email
f
Using an HTML table with DataTable
f
Using an HTML table with DataTable and a database
f
Using word_limiter() for table output
f
Using word_censor() for cleaning input
Introduction
CodeIgniter comes with some useful libraries and functions for handling many aspects of application development. In this chapter we will look at Email and HTML tables. The CodeIgniter Email library is capable of sending plain text and HTML e-mails, with and without attachments that can be used (with a little configuration) instead of the standard PHP mail() function.
CodeIgniter's HTML Table library is excellent at generating the HTML necessary for pretty much most of what you will need a table for—and, together with DataTable, can provide excellent interactive tables for your users.
Email, HTML Table, and Text Libraries
Sending plain e-mails with CodeIgniter Email
It's always useful to be able to send e-mails and CodeIgniter comes with an excellent library for sending e-mails. There are a few recipes in this chapter, which deal with sending e-mails.
However, this is the basic Hello World type example that is very simple.
How to do it...
A simple way to send plain e-mails using CodeIgniter Email is as follows: 1. Create a file email.php at path/to/codeigniter/application/
controllers/.
2. Add the following code to the controller file email.php:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Email extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->helper('url');
$this->load->library('email');
}
public function index() {
redirect('email/send_email');
}
public function send_email() {
$config['protocol'] = 'sendmail';
$config['mailpath'] = '/usr/sbin/sendmail';
$config['charset'] = 'iso-8859-1';
$config['wordwrap'] = TRUE;
$config['mailtype'] = 'text';
$this->email->initialize($config);
$this->email->from('from@domain.com', 'Your Name');
$this->email->to('to@domain.com');
$this->email->subject('This is a text email');
$this->email->message('And this is some content for
the text email.');
$this->email->send();
echo $this->email->print_debugger();
}
}
70
Chapter 4
How it works...
In the constructor controller we load the Email library (highlighted in the following code), which provides support to send e-mails:
function __construct() {
parent::__construct();
$this->load->helper('url');
$this->load->library('email');
}
Next, public function index() redirects us to the function public function send_mail(), which sets some initial configuration variables for CodeIgniter Email library to work with, such as the system used to send the e-mail (in this case, sendmail), the path to send e-mail on your system, the mailtype variable (text or HTML), and so on. Take a look at the following line of code:
$config['mailtype'] = 'text';
Here, we're telling CodeIgniter to send the e-mail as just plain text rather than HTML.
These configuration settings are initialized (that is, passed to the Email library), and we begin to build the e-mail by setting the to, from, subject, and message attributes: $this->email->from('from@domain.com', 'Your Name');
$this->email->to('to@domain.com');
$this->email->subject('This is a text email');
$this->email->message('And this is some content for the text email.');
Then, send the e-mail:
$this->email->send();
If all works out as planned, you should see an output similar to the following one: User-Agent: CodeIgniter
Date: Fri, 4 Oct 2013 08:51:03 +0200
From: "Your Name" <from@domain.com>
Return-Path: <from@domain.com>
To: to@domain.com
Subject: =?iso-8859-1?Q?This_is_a_text_email?=
Reply-To: "from@domain.com" <from@domain.com>
X-Sender: from@domain.com
X-Mailer: CodeIgniter
X-Priority: 3 (Normal)
Message-ID: <524e6557968c5@domain.com>
71
Email, HTML Table, and Text Libraries
Mime-Version: 1.0
Content-Type: text/plain; charset=iso-8859-1
Content-Transfer-Encoding: 8bit
And this is some content for the text email.
Sending HTML e-mails with CodeIgniter
There might be times when you wish to display formatted e-mails rather than just plain text, so you may wish to include images, text formatting, and URLs in the body of your e-mail. HTML e-mails will allow you to do this and CodeIgniter Email library can easily be set to do just that.
How to do it...
HTML e-mails can be sent by executing the following steps:
1. Create a file email.php at /path/to/codeigniter/application/
controllers/.
2. Add the following code to the controller file email.php:
<?php if ( ! defined('BASEPATH')) exit('No direct script
access allowed');
class Email extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->helper('url');
$this->load->library('email');
}
public function index() {
redirect('email/send_email');
}
public function send_email() {
$config['protocol'] = 'sendmail';
$config['mailpath'] = '/usr/sbin/sendmail';
$config['charset'] = 'iso-8859-1';
$config['wordwrap'] = TRUE;
72
Chapter 4
$config['mailtype'] = 'html';
$this->email->initialize($config);
$this->email->from('from@domain.com', 'Your Name');
$this->email->to('to@domain.com');
$this->email->subject('This is a html email');
$html = 'This is an <b>HTML</b> email';
$this->email->message($html);
$this->email->send();
echo $this->email->print_debugger();
}
}
How it works...
In the constructor controller we load the Email library (highlighted in the following code), which provides support for us to send e-mails:
function __construct() {
parent::__construct();
$this->load->helper('url');
$this->load->library('email');
}
Next, public function index() redirects us to the function public function send_mail(), which sets some initial configuration variables for CodeIgniter Email library to work with, such as the system used to send the e-mail (in this case, sendmail), the path to send e-mail on your system, the mailtype variable (text or HTML), and so on. Take a look at the following line of code:
$config['mailtype'] = 'html';
Here, we're telling CodeIgniter to send the e-mail as HTML rather than as text.
These configuration settings are initialized (that is, passed to the Email library) and we begin to build the e-mail by setting the to, from, subject, and message attributes: $this->email->from('from@domain.com', 'Your Name');
$this->email->to('to@domain.com');
$this->email->subject('This is a text email');
$this->email->message('And this is some content for the text email.');
Then, send the e-mail using the following code:
$this->email->send();
73
Email, HTML Table, and Text Libraries
If all works out as planned, you should see an output similar to the following code: Your message has been successfully sent using the following protocol: sendmail
User-Agent: CodeIgniter
Date: Fri, 4 Oct 2013 08:56:59 +0200
From: "Your Name" <from@domain.com>
Return-Path: <from@domain.com>
To: to@domain.com
Subject: =?iso-8859-1?Q?This_is_a_html_email?=
Reply-To: "from@domain.com" <from@domain.com>
X-Sender: from@domain.com
X-Mailer: CodeIgniter
X-Priority: 3 (Normal)
Message-ID: <524e66bbf282f@domain.com>
Mime-Version: 1.0
Content-Type: multipart/alternative; boundary="B_ALT_524e66bbf2868"
This is a multi-part message in MIME format.
Your email application may not support this format.
--B_ALT_524e66bbf2868
Content-Type: text/plain; charset=iso-8859-1
Content-Transfer-Encoding: 8bit
This is an HTML email
--B_ALT_524e66bbf2868
Content-Type: text/html; charset=iso-8859-1
Content-Transfer-Encoding: quoted-printable
This is an <b>HTML</b> email
--B_ALT_524e66bbf2868--
Sending attachments with CodeIgniter Email
There might be times when you wish to send an attachment along with the e-mail, such as an invoice to a customer for a recent purchase or perhaps an image. The CodeIgniter Email library can easily be set to do just that.
74
Chapter 4
How to do it...
You can send attachments with CodeIgniter Email by executing the following steps: 1. Create a file email.php at /path/to/codeigniter/application/
controllers/.
2. Add the following code to the controller file, email.php:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Email extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->helper('url');
$this->load->library('email');
}
public function index() {
redirect('email/send_email');
}
public function send_email() {
$config['protocol'] = 'sendmail';
$config['mailpath'] = '/usr/sbin/sendmail';
$config['charset'] = 'iso-8859-1';
$config['wordwrap'] = TRUE;
$config['mailtype'] = 'html';
$this->email->initialize($config);
$this->email->from('from@domain.com', 'Your Name');
$this->email->to('to@domain.com');
$this->email->subject('This is a html email');
$html = 'This is an <b>HTML</b> email with an attachment,
<i>lovely!</i>';
$this->email->message($html);
$this->email->attach('/path/to/attachment');
$this->email->send();
echo $this->email->print_debugger();
}
}
75
Email, HTML Table, and Text Libraries
How it works...
In the constructor controller we load the Email library (highlighted in the following code), which provides support to send e-mails:
function __construct() {
parent::__construct();
$this->load->helper('url');
$this->load->library('email');
}
Next, public function index() redirects us to the function, public function send_mail(), which sets some initial configuration variables for the CodeIgniter Email library to work with, such as the system used to send the e-mail (in this case, sendmail), the path to send mail on your system, the mailtype variable (text or HTML), and so on.
These configuration settings are initialized (that is, passed to the Email library) and we begin to build the e-mail; setting the to, from, subject, and message attributes, as well as the path to the attachment we're sending in the e-mail (highlighted in the following code): $this->email->from('from@domain.com', 'Your Name');
$this->email->to('to@domain.com');
$this->email->subject('This is a html email');
$html = 'This is an <b>HTML</b> email with an attachment,
<i>lovely!</i>';
$this->email->message($html);
$this->email->attach('/path/to/attachment');
Then, send the e-mail using the following code:
$this->email->send();
Sending bulk e-mails with CodeIgniter Email
There may be times when you wish to send out bulk e-mails; perhaps to all the people who have paid to go on a tour. You may wish to send them each a personalized e-mail, and also add an attachment. You may also want to pull their e-mail preference (plain text or HTML) from the account on your database and send them the correct format of e-mail. That's what we're going to do here.
76
Chapter 4
Getting ready
We need to know each person's preferences such as whether they want HTML e-mails or text, and also their individual reference number (or booking ID) for their trip. As per this requirement, we are going to have a database to hold all the information; so copy the following code into your database:
CREATE TABLÈbookers` (
ìdìnt(11) NOT NULL AUTO_INCREMENT,
`firstnamè varchar(50) NOT NULL,
`lastnamè varchar(50) NOT NULL,
èmail` varchar(255) NOT NULL,
èmail_pref` varchar(4) NOT NULL,
`booking_ref` varchar(10) NOT NULL,
PRIMARY KEY (ìd`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
INSERT INTÒbookers` (ìd`, `firstnamè, `lastnamè, èmail`,
èmail_pref`, `booking_ref`) VALUES
(1, 'Robert', 'Foster', 'example1@domain1.com', 'html', 'ABC123'), (2, 'Lucy', 'Welsh', 'example2@domain2.com', 'html', 'DEF456');
How to do it...
1. Create a file email.php at /path/to/codeigniter/application/
controllers/.
2. Add the following code to the controller file, email.php:
<?php if ( ! defined('BASEPATH')) exit('No direct script
access allowed');
class Email extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->helper('url');
$this->load->library('email');
}
public function index() {
redirect('email/send_email');
}
public function send_email() {
$config['protocol'] = 'sendmail';
$config['mailpath'] = '/usr/sbin/sendmail';
$config['charset'] = 'iso-8859-1';
$config['wordwrap'] = TRUE;
$query = "SELECT * FROM bookers ";
$result = $this->db->query($query);
77
Email, HTML Table, and Text Libraries
foreach ($result->result() as $row) {
$this->email->clear();
if ($row->email_pref == 'text') {
$config['mailtype'] = 'text';
$body = 'Hi ' . $row->firstname . ',
Thanks you for booking with us, please
find attached the itinerary for your
trip. This is your booking reference
number: ' . $row->booking_ref . '
Thanks for booking with us, have a
lovely trip.';
} else {
$config['mailtype'] = 'html';
$body = 'Hi ' . $row->firstname . ',
<br /><br />Thanks you for booking with
us, please find attached the itinerary
for your trip. </p>This is your booking
reference number: <b>' .
$row->booking_ref . '</b><br />
<br />Thanks for booking with us,
have a lovely trip.';
}
$this->email->initialize($config);
$this->email->to($row->email);
$this->email->from('
bookings@thecodeigniterholidaycompany.com');
$this->email->subject('
Holiday booking details');
$this->email->message($body);
$this->email->send();
}
echo $this->email->print_debugger();
}
}
How it works...
In the constructor controller we load the Email library (highlighted in the following code), which provides support for us to send e-mails:
function __construct() {
parent::__construct();
$this->load->helper('url');
$this->load->library('email');
}
78
Chapter 4
Next, public function index() redirects us to the function, public function send_mail(), which sets some initial configuration variables for CodeIgniter Email library to work with, such as the system used to send the e-mail (in this case, sendmail), the path to send mail from your system.
We then query the database for each of the customer's booking details: $query = "SELECT * FROM bookers ";
$result = $this->db->query($query);
foreach ($result->result() as $row) {
}
The query will loop through each result and send a specific e-mail based on the values retrieved from the database in each loop.
Firstly, we give ourselves a clean slate by clearing all the settings and variables from a previous loop iteration by using the CodeIgniter email function:
$this->email->clear();
We then look at their e-mail preference and set the e-mail sending (mailtype) variable accordingly, along with the text for the body of the e-mails. So, if someone prefers HTML, we look for that preference and define the body of the HTML e-mail, otherwise for a text e-mail, we look for the text e-mail preference and define the body for the text e-mail: if ($row->email_pref == 'text') {
$config['mailtype'] = 'text';
$body = 'Hi ' . $row->firstname . ',
Thank you for booking with us, please find attached the
itinerary for your trip.
This is your booking reference number: ' .
$row->booking_ref . '
Thanks for booking with us, have a lovely trip.';
} else {
$config['mailtype'] = 'html';
$body = 'Hi ' . $row->firstname . ',<br /><br />
Thank you for booking with us, please find attached the
itinerary for your trip. </p>
This is your booking reference number: <b>' .
$row->booking_ref . '</b><br /><br />
Thanks for booking with us, have a lovely trip.';
}
79
Email, HTML Table, and Text Libraries
After this, we initialize the configuration variables. Those of you who have looked at the previous few recipes will notice that the initialization takes place later in the code of this recipe than in others. This is because we cannot initialize the config variables earlier as some of the variables rely on the preferences of individual customers, which are fetched from the database. So, we have to wait until each user's details are fetched from a database to initialize each iteration of the configuration settings. And finally, we send the e-mail: $this->email->send();