CodeIgniter Database Connection Error

I have started learning how to use the PHP framework CodeIgniter. I’m not a professional coder, but I have dabbled with PHP and various other languages over the years.

As I’m new to the framework, the first order of business was to follow the tutorial to setup a basic application using CodeIgniter. I thought that this would be a fairly quick and easy thing to follow and then I could get on to playing about with it further. About 5 hours later and I finally got to the end of the tutorial with the sample app in working order. This post describes the first issue I came across and how I eventually resolved it.

The Problem

So, I had setup my database and configured username, password and database name correctly in the application/config/database.php file but was getting the following error when trying to access it from the CodeIgniter app.

A Database Error Occurred
Unable to connect to your database server using the provided settings.
Filename: core/Loader.php
Line Number: 346

I double-checked and triple-checked my database settings, and even setup a quick plain PHP test script to make sure I could connect to it and retrieve results successfully, which worked fine.

The Solution

After hours of reading posts from people with similar issues and trying various things, checking and re-checking all my settings etc., the following change fixed it for me.

In application/config/database.php change…

$db['default']['pconnect'] = TRUE;


$db['default']['pconnect'] = FALSE;

It seems to me that some web hosts maybe don’t like persistent database connections, and I guess my host is one of them!

Other Useful Information

Also worth mentioning here is a nice bit of code to add to the end of your application/config/database.php file to help troubleshooting database connection issues. In my case it actually connected without a problem (which at least confirmed that my connection settings were fine), but I read of others who found it very useful. Note that I didn’t write this myself, I found it on a few different posts from different people so not sure who to give credit to.

echo '<pre>';
echo '</pre>';

echo 'Connecting to database: ' .$db['default']['database'];
  or die('Cannot connect to the database because: ' . mysql_error());
  mysql_select_db ($db['default']['database']);

echo '<br /> Connected OK: '  ;
die( 'file: ' .__FILE__ . ' Line: ' .__LINE__);

Using this code you should be able to pinpoint where your connection issue lies.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>