Best method of connecting to a database (Multiple Queries)

Discussion in 'PHP' started by thing2b, Mar 6, 2008.

  1. #1
    Lately I seem to have been having a few problems with my PHP app. Every now and then the logs would show "Not enough database connections". Recently the errors have been more like "Not enough memory".

    I realised today what the real problem was and was wondering what people thought about it.

    The problem that I had seems to be caused by having more than one query connected at a time. My most used database code goes something like this:

    (Although I am using Zend Framework style here it should not matter)

    
    $stmt = $db->query($sql);
    while ($row = $stmt->fetch()) {
        $someClass->method($row['title']);
        echo $row['title'];
    }
    
    Code (markup):
    But then in $someClass->method I would be doing more database stuff.

    
    function method(){
        while ($row = $stmt->fetch()) {
            echo $row['somethingelse'];
        }
    }
    
    Code (markup):
    Now here are my questions:
    - Am I right, assuming that every separate SQL query (connected at the same time) requires it's own database connection?
    - Do multiple database connections use a significant amount of memory?
    - Has anyone else hit this?
    - Does anyone have another way of coding this?

    The code by the way was fixed by getting all the data from the SQL query at once, so that I did not need to be fetching from the database every loop. Something like this:

    
    $stmt = $db->query($sql);
    $allData = $stmt->fetchAll()
    foreach( $allData as $rows){
        $someClass->method($row['title']);
        echo $row['title'];
    }
    
    Code (markup):
     
    thing2b, Mar 6, 2008 IP
  2. jestep

    jestep Prominent Member

    Messages:
    3,659
    Likes Received:
    215
    Best Answers:
    19
    Trophy Points:
    330
    #2
    Unless there's some major issues with the connection class, in your examples, there should only be a single connection. Normally it would work like this:

    Connect to database ->
    Query as many times as you want.....
    Close connection

    If not coded correctly, it could be doing this:
    Connect to database->
    Query once
    Close connection
    ...Repeat

    Did you code the connection and querying class yourself. You should definitely be using a singleton database class which will prevent multiple connection on a single script.
     
    jestep, Mar 7, 2008 IP