newbie
newbie

Reputation: 14960

PHP Mysql Configuration - Too many connections

Good day!

I have a website deployed in a free web-hosting server. Recently, I cannot access my SQL and receive this warning: too many connections.

MY CODES:

In order to access mysql, i created a config.php file.

 <?php
        // save this as config.php
        define('DB_HOST', 'localhost');
        define('DB_USER', 'username');
        define('DB_PASSWORD', 'password');
        define('DB_DATABASE', 'pascual4_eventpost');
        $conn=mysql_pconnect(DB_HOST, DB_USER, DB_PASSWORD)
          or die ("Error connecting to database");
        mysql_select_db(DB_DATABASE)
          or die ("Error: Cannot access database");
    ?>

So If ever I need to access my database. I just call require("config.php");

I've read somewhere before that mysql connections automatically closes when the script is done. That's why I don't put any mysql close connection code on my PHP pages. Or do I still need to close it manually and input mysql_close($conn); on every page?

So I restarted my PC and flush my dns. Luckily, now I can access my mysql database but it is very slow. Maybe because I am using a free-web hosting? But, on my part, is there a way where I can speed-up my mysql connection and queries. What Validations can I include on the above code so that I could improve the performance of my mysql connection? Thank you.

Upvotes: 1

Views: 1184

Answers (3)

John Parker
John Parker

Reputation: 54445

As you state, PHP will close any open connections when your script terminates, so unless you're tying up connections by executing long-running scripts/queries, etc. then this is most likely a symptom of a very low max_connections mysqld setting, which isn't a huge surprise bearing in mind that you're using a free hosting package.

I'm not sure how many connections you're using per "page", but:

  1. In my experience using mysql_pconnect generally makes the situation worse, rather than better. (Just use mysql_connect.)

  2. If you're using multiple connections on the same page, it would be an idea to re-use the same database connection if at all possible.

Failing that, it might be time to look for a more appropriate hosting package.

Upvotes: 2

Your Common Sense
Your Common Sense

Reputation: 158005

    $conn=mysql_connect(DB_HOST, DB_USER, DB_PASSWORD)
    remove p here^

To solve the problem from the question title.

As for the database performance it's hard to tell from such a vague description like "it is very slow". What is certainly slow? Connect itself? Did you measure it? Some queries? Which queries?

Upvotes: 1

Ian Wood
Ian Wood

Reputation: 6573

When you use persistent connections you can get this connection leak.

Have you considered not using persistent connections? or using the mysqli library or pdo class andallow these to manage this for you?

Upvotes: 1

Related Questions