Introduction

Today we’re going to be learning how to connect and then query a database in CodeIgniter. Knowing how to manipulate and read databases is an essential tool for creating any dynamic web application. Let’s get started.

Prerequisites

We will be using a MySQL database, and for the scope of this tutorial we will not be explaining how to create and populate a MySQL database. If you need help creating a database to test your connection and query on check out the MySQL documentation. You’ll also need to know how to create and set up CI routes, controllers, and views. If you need help setting those up check out Get Up & Running with CodeIgniter.

Our Database

Our database only has two columns and one entry. It’s as simple as it could get for the purpose of this tutorial. We have a primary key of id with our entry’s value as 1, and we have a name property with the value as Kanye West.

Our database information:

  • Name: test
  • User: root
  • Host: localhost
  • Driver: MySQL

That’s all for the database so let’s get into the application’s setup.

Our Application

Our demo application consists of one view by the name of index.php with the following code within it:

Wiring up the DB

To configure our database we need to locate /application/config/database.php and change the following settings:

Make sure you are filling in this information with the correct information for your specific database setup. For a list of native database engines that CI supports visit their documentation.

Setting up the Controller and Querying the DB

Normally we would create a model for making complex database queries and assign different methods to the model class but since we only have one object in our db, let’s just demonstrate how to query the database and pass it into $data for the view.

Create a new Controller named test.php:

We’re querying our database above by id, and then storing the key value pairs into an object named $value. Then we call the specific name property of $value to be passed into our view.

Route Configuration

Now we have to configure the route to our view, since we only have a simple view, all we have to do is type the following in /application/config/routes.php:

Conclusion

Navigate to your local CI server and you should see that your root view displays the following:

kanye

Congratulations! You did it, you now have the knowledge required to connect and query databases in CodeIgniter and you’re one step closer to creating dynamic CI web applications.