【发布时间】:2015-03-26 00:16:10
【问题描述】:
我在保持连接的 PDO 数据库连接方面遇到了一些小问题。
我正在运行的代码正在向 twitter 自动发布一些帖子。 我每小时通过 CRON 运行一次代码,但为了节省一次性将所有消息发布到 twitter,我在每个循环后使用 sleep()。
这 (sleep()) 导致数据库连接保持打开状态,直到脚本完成运行。 为了尝试阻止这种情况,我添加了各种方法来“强制关闭”连接,但它们似乎都不起作用。 返回结果后就不需要连接了。
下面是我正在使用的代码(为这篇文章做了一点简化)
$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
}
}
带有查询的类文件(提取)
/*
* 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;
}
}
任何关于我如何做我想做的事但在查询运行后关闭连接的建议,将不胜感激! 谢谢!
【问题讨论】: