0

I have having some small problems with a PDO database connection remaining connected.

The code i am running is making some automated posts to twitter. I run the code via CRON once an hour, but to save posting all messages to twitter in one go, i user sleep() after each loop.

This (sleep()) is resulting in keeping the database connection open until the script finished running. To try and stop this, i have added in variouse methods to "force close" the connection, but none of them seem to be working. The connection is not required once the results are returned.

Below is the code i am using (simplified a little for this post)

$escort_obj = new MLE_Escort();
if($result = $escort_obj->getRandomEscortsSearch($limit = 5)){

    foreach ($result AS $row) {

        // set the data we need //

        // assign image
        $image = '..'.$row->PhotoURL;

        // build tags
        $tags = '#Escorts ';
        if(!empty($row->InCallLocation)) {
            $tags .=  '#'.str_replace(' ', '', $row->InCallLocation).' ';
        }

        // join the data into the $tweet
        $tweet =  strip_tags($row->Description).' '.$tags;

        // call function to post to twitter
        postToTwitter($image, $tweet, $tmhOAuth);

        sleep(500); // sleep a while
    }
}

Class file (extract) with query

    /*
     * get random profiles for posting to twitter
     * @return result of the mySQL query
     */
    public function getRandomEscortsSearch($limit)
    {
        try
        {

            $query = "SELECT 
                        e.EscortID,
                        e.EscortName,
                        e.DateModified,         
                        LEFT(e.InCallLocation, 25) AS InCallLocation,
                        e.InCallLocation AS FULLInCallLocation,
                        e.HairColour,
                        LEFT(e.EscortProfile, 85) AS Description,
                        p.PhotoURL
                        FROM tEscort e
                        INNER JOIN (tEscortPhoto ep INNER JOIN tPhoto p ON (ep.tPhoto_PhotoID = p.PhotoID AND p.Enabled=1)) 
                            ON e.EscortID = ep.tEscort_EscortID AND ep.ProfilePhoto = 1
                        INNER JOIN tUser u ON u.UserName = e.PrivateEmail
                        INNER JOIN tmembers m ON m.tUser_UserID = u.UserID
                        WHERE e.Enabled = 1
                        AND e.Active = 1
                        AND m.tMemberStatuses_MemberStatusID = 2
                        AND e.tEscortMembership_MembershipID != 6
                        ORDER BY rand()
                        LIMIT ?";       
            $stmt = $this->conn->prepare($query);
            $stmt->execute(array($limit));
            $result = $stmt->FetchAll(PDO::FETCH_OBJ);
            $this->conn = NULL; // force close DB
            $stmt = NULL; // empty $stmt
            $dbPDO = NULL; // force close this too in case it was open
            return $result; // return reults
        }
        catch (PDOException $ex) {
            // do some stuff (removed to keep this question clean)
            return false;
        }
    }

Any advice on how i can do what i want but also close the connection once the query has ran, would be much appreciated ! Thanks!

Ford
  • 537
  • 6
  • 20

1 Answers1

0

This isn't that serious if you don't. Upon successful connection to the database, an instance of the PDO class is returned to your script. The connection remains active for the lifetime of that PDO object. To close the connection, you need to destroy the object by ensuring that all remaining references to it are deleted--you do this by assigning NULL to the variable that holds the object. If you don't do this explicitly, PHP will automatically close the connection when your script ends.

http://php.net/manual/en/pdo.connections.php

So the answer is no, you don't need to do anything unless you need to explicitly close the connection during the script execution for whatever reason, in which case just set your PDO object to null.

unixmiah
  • 3,081
  • 1
  • 12
  • 26
  • 1
    That's what I thought first, too. However, have a look at the comment of "Vicente" on the documentation page you have linked to (http://php.net/manual/en/pdo.connections.php) – Jan Mar 25 '15 at 16:19
  • is assigning the results to $result still classed as an object that would need to be assigned NULL then? the problem is i still need $result within the loop – Ford Mar 25 '15 at 16:19
  • i dont think it is a problem either, but the host is suggesting it is causing the database server to not respond... i dont believe this is the cause, but i have to fix it first to prove myself – Ford Mar 25 '15 at 16:21
  • hmn.. if you are able to pull data from the connection you should be able to close it. For example, if you have $link = new PDO("mysql:dbname=$dbname;host=$servername",$username,$password); as a connection you should be able to do $link = null; to close the connection. – unixmiah Mar 25 '15 at 16:57
  • @unixmiah. i am unable to reconnect after i do (as you say) $link = NULL; but the db connection is still "active" from the previous connection (i assume). I can see the connection is "active" in MySQL Administrator. it closes once the scrip finishes. I have tried assigning the SQL result to an array with a foreach loop and $result_arr[] = $row... but again the connection is remaining "active" until the script finishes – Ford Mar 25 '15 at 17:18