Original: Use CodeIgniter to create a simple Web site
References from:
Http://www.ibm.com/developerworks/cn/web/wa-codeigniter/index.html
My first CodeIgniter project (except for HelloWorld) is now collated and recorded.
Related environment:
System: ubuntu-10.04.3
apache:httpd-2.4.7
php:php-5.4.22
mysql:mysql-5.6.16
ci:codeigniter-2.2.0
Goal:
Use CodeIgniter to create a simple Web site. The site will have a home page that displays some promotional text and a form that will be published to the database table.
In terms of codeigniter, these requirements can be converted to the following:
- A controller that contains only a few features (you can also use the default Welcome controller)
- A model (and a database table) for storing contact information
- A main view that contains some support
I. Creating database tables and Models
Starting with a model helps you understand the underlying database tables before you start laying out features and UI. Designing forms that interact with tables is difficult if you don't understand what the table will store.
For this sample application, you want to store contact information from the form. What types of contact information are needed? For now, only basic information is stored and requires a name, email address, phone number, and a short note. You may also want to store timestamps and IP addresses in the background.
1. Create a database table
Cd/usr/local/mysql/bin
Mysql-u root-p
Then enter the password (I'm root here) and go to MySQL.
To see which databases are available, command: show databases;
To create a database, you can use the command: Create database Tina; (Here I have created a db named Tina)
Select the database to be used: use Tina; (using a database called Tina)
To create a table contacts:
CREATE TABLE ' contacts ' (
' id ' int (one) not NULL auto_increment,
' Name ' varchar (+) is not NULL,
' Email ' varchar (255) Not NULL,
' Notes ' text is not NULL,
' Stamp ' timestamp not NULL the default current_timestamp on update Current_timestamp,
' IPAddress ' varchar (+) not NULL,
PRIMARY KEY (' id ')
) Engine=myisam;
View the names of all tables under the current database: show tables;
View Contacts Table structure: DESC contacts; or show columns from contacts;
View data in table contacts: SELECT * from contacts;
Configuration:
The most important folder in the application Folder is config. There are two files in this folder that need attention: config.php and database.php.
The config.php file contains the basic parameters and arguments that are required to set up CodeIgniter. The database.php file contains the basic parameters and arguments that are required to connect to the database.
For config.php files, just set the base_url
parameters, for example, set to http://localhost/CodeIgniter_2.2.0/.
This setting is changed according to the server address currently in use:
$config [' base_url '] = ' http://localhost/CodeIgniter_2.2.0/'
It is important to remember to add the last slash, even if you set the CodeIgniter application in a subdirectory.
Open the database.php file below to set the connection parameter for the database server:
$db [' Default '] [' hostname '] = "your-db-host"; $db [' Default '] [' username '] = ' your-username '; $db [' Default '] [' Password ' ] = "Your-password"; $db [' Default '] [' database '] = "your-db-name"; $db [' Default '] [' dbdriver '] = "MySQL";
For example:
2. Create a model
Within the Application/models folder, create a contacts_model.php file.
The code is as follows:
<?PHPclassContacts_modelextendsci_model{function__construct () {Parent::__construct (); } Public functionadd_contact () {Date_default_timezone_set (' UTC '); $now=Date("Y-m-d h:i:s");
$data=Array( ' Name ' + =$this->input->post (' name '), ' email ' =$this->input->post (' email '), ' notes ' =$this->input->post (' Notes '), ' ipaddress ' =$this->input->ip_address (), ' stamp ' =$now ); $this->db->insert (' Contacts ',$data); }}/*End of File contacts_model.php*//*Location :./application/controllers/contacts_model.php*/
In the code above, it was actually used to $this->input->xss_clean()
sort the data of the form field, but there was a problem, that is, a blank page was displayed after the form was submitted. It is unclear what the reasons are, pending further study.
Second, the initialization of the controller
In CodeIgniter, the controller is used to organize the project. Imagine that each function is a page or destination for a site or application. If you use a home page, you need a index()
function. If you have a about Us page, you need about()
or about_us()
function-depending on how you want to construct the URL.
You can even organize your controllers into folders to create hierarchies. For example, in the System/application/controllers folder, there may be an admin folder that contains controllers for the main parts of the management tool. These controllers (and functions) can be accessed as follows: http://www.example.com/admin/controller-name/function-name/.
Go to the application/controllers/folder and create a new contacts.php file. (Of course, you can also use the default controller, the Welcome controller.) )
The code is as follows:
<?PHP/** * Contacts Class * * @author Tina*/classContactsextendsci_controller{function__construct () {Parent::__construct (); } functionindex () {$this->load->helper (' form '); $data[' title '] = "Welcome to our Site"; $data[' headline '] = "welcome!"; $data[' include '] = ' contacts_home '; $this->load->vars ($data); $this->load->view (' Contacts_view '); }};/*End of File contacts.php*//*Location :./application/controllers/contacts.php*/
Set up multiple variables that can be used inside a view-this way, you can better organize your application. For example, you might want to set the title and title bar in the controller. If you do this, you must load the variable into the view. One of the variables that is loaded is the name of the contained view. In this way, you can set the main view that contains all the skins, and each containing item that contains the content.
上面代码中$data
The array is passed into a view (Contacts_view). The information inside the array can be accessed using the key name, if you want to output the title bar by $headline
accessing it.
Next, you will create the view and complete the controller.
Third, create a view
In Application/views, create a file named contacts_view.php.
The code is as follows:
Echo $title Echo $headline $this->load->view ($include);? ></body>
The above code passed in three variables: $title
, $headline
and $include
(the name of a containing item).
In the first two PHP statements, the data found in and are displayed separately $data[‘title‘]
$data[‘headline‘]
. $data[‘include‘]
the values that are then used are loaded into the second view. In this case, a view named Contacts_home (with a little CSS code added). It contains a block of text and a form that collects information from site visitors:
contacts_home.php
The code is as follows:
<p>this is the random text forThe CodeIgniter article.there‘s nothing to see here folks, just move along!</p>' Contacts/contactus '); Echo Form_label (' Your name ', ' name '); $ndata = Array (' Name ' = ' ' name ', ' id ' = ' id ', ' size ' = ' 25 'Echo Form_input ($ndata); Echo Form_label (' Your email ', ' email '); $edata = Array (' Name ' = ' email ', ' id ' = ' email ', ' size ' = ' 25 'Echo Form_input ($edata); Echo Form_label (' How can I help you? ', ' Notes '); $cdata = Array (' Name ' = ' Notes ', ' id ' = ' notes ', ' cols ' = ' + ', ' Rows ' and ' 5 'Echo Form_textarea ($cdata); Echo Form_submit (' Submit ', ' send us a note '); Echo Form_close ();? >
The Form helper is used here to load it into the controller. form_open()
The function allows the form to be opened-it has the necessary arguments, that is, the target location of the form's publication. Next, the controller is returned and a function is added contact()
to process the form publishing data.
In the form, use to form_label()
create accessible labels, use form_input()
and form_textarea()
to build form fields and text areas, and use form_submit()
to build input buttons. Here, through form_input()
and form_textarea()
(and other form functions), you can pass in an array of information to help track field names, IDs, sizes, and other information.
Finally, use the form_close()
close form.
Then create a view file contacts_thanks.php.
The code is as follows:
< P > Thanks so much for contacting us. Someone'll is in the contact with you soon. </ P >
Iv. completion of the controller You now need to go back to the controller contacts.php and add two functions to it.
① handles the functions of the form's incoming POST on the home page contactus()
.
The ② thankyou()
function, which will be used as the final confirmation page for the form.
contactus()
The function is very simple. Load the Contacts_model model, run the functions within the model, add_contact()
and then turn the user into the Thanks page. Note that to use redirect()
a function, you must load the URL helper.
The function code looks like this:
functionContactUs () {$this->load->helper (' url ');$this->load->model (' Contacts_model ', ',TRUE); $this->contacts_model->add_contact (); Redirect (' Contacts/thankyou ', ' Refresh '); } functionthankyou () {$data[' title '] = "Thank you!"; $data[' headline '] = "thanks!"; $data[' include '] = ' contacts_thanks '; $this->load->vars ($data); $this->load->view (' Contacts_view '); }
Five, add security In the controller's contactus()
function, there is a risk of creating multiple empty records in the database-which causes someone to continuously load the contact target into their browser or use some type of robot. The simplest way to avoid this kind of situation is to add a simple test to the controller. If POST
data exists, the model and function are loaded. If not, it is returned to the home page.
The modified function is as follows:
functionContactUs () {$this->load->helper (' url '); if($this->input->post (' email ')) { $this->load->model (' Contacts_model ', ',TRUE); $this->contacts_model->add_contact (); Redirect (' Contacts/thankyou ', ' Refresh '); } Else{Redirect (' Contacts/index ', ' Refresh '); } }
Conclusion At this point, you create a Web site that contains a home page, a form that adds information to the database, and a thanks page.
Of course, there are many things to learn. For example, you can automatically load the desired model and any helper or library, adjust the cache and performance for the application, add more CSS content to the view, and add the ability to send e-mail notifications after the database insert operation ends.
Come on!
Use CodeIgniter to create a simple Web site