2 Comments

Database Quick Start: Example Code

The following page contains example code showing how the database class is used. For complete details please read the individual pages describing each function.

Initializing the Database Class

The following code loads and initializes the database class based on your configuration settings:

$this->load->database();

Once loaded the class is ready to be used as described below.

Note: If all your pages require database access you can connect automatically.

Standard Query With Multiple Results (Object Version)

$query = $this->db->query('SELECT name, title, email FROM my_table');
foreach ($query->result() as $row)
{
    echo $row->title;
    echo $row->name;
    echo $row->email;
}
echo 'Total Results: ' . $query->num_rows();

The above result() function returns an array of objects. Example: $row->title

Standard Query With Multiple Results (Array Version)

$query = $this->db->query('SELECT name, title, email FROM my_table');
foreach ($query->result_array() as $row)
{
    echo $row['title'];
    echo $row['name'];
    echo $row['email'];
}

The above result_array() function returns an array of standard array indexes. Example: $row[‘title’]

Testing for Results

If you run queries that might not produce a result, you are encouraged to test for a result first using the num_rows() function:

$query = $this->db->query("YOUR QUERY");
if ($query->num_rows() > 0)
{
   foreach ($query->result() as $row)
   {
      echo $row->title;
      echo $row->name;
      echo $row->body;
   }
}

Standard Query With Single Result

$query = $this->db->query('SELECT name FROM my_table LIMIT 1');
$row = $query->row();
echo $row->name;

The above row() function returns an object. Example: $row->name

2 comments on “Database Quick Start: Example Code

  1. Very informative post, i’m regular reader of your blog.
    I noticed that your blog is outranked by many
    other blogs in google’s search results. You deserve to be in top-10.
    I know what can help you, search in google for:
    Mosis’s Tips Outsource The Work

    Liked by 1 person

Leave a comment