mysql连接警告太多了

时间:2014-09-10 17:55:29

标签: php mysql

运行此cron作业时,我一直收到以下错误。它每分钟运行一次:

错误

    <br />
<b>Warning</b>:  mysqli_connect(): (08004/1040): Too many connections in <b>/home/eterna33/public_html/script/email_cron.php</b> on line <b>2</b><br />


    <br />
    <b>Warning</b>:  mysqli_query() expects parameter 1 to be mysqli, boolean given in <b>/home/eterna33/public_html/script/email_cron.php</b> on line <b>6</b><br />
    <br />
    <b>Warning</b>:  mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given in <b>/home/eterna33/public_html/script/email_cron.php</b> on line <b>8</b><br />
    <br />
    <b>Warning</b>:  mysqli_close() expects parameter 1 to be mysqli, boolean given in <b>/home/eterna33/public_html/script/email_cron.php</b> on line <b>19</b><br />

以下是每分钟在cron作业中运行的代码。

<?php
$con=mysqli_connect("localhost","**","****","***");



$result = mysqli_query($con, "SELECT * FROM mail WHERE status=false");
$count="0";
while($row = mysqli_fetch_array($result)) {
        $count++;
        mysqli_query($con, "UPDATE mail SET status=true WHERE id='$row[id]'");
        mail($row['send_to'], $row['subject'], $row['message'], $row['headers']);
        mysqli_query($con, "DELETE FROM mail WHERE status=true AND id='$row[id]'");
        if ($count >= 3) {
            echo "exit";
            mysqli_close($con);

            exit;
        }
    }

mysqli_close($con);
?>

我已经联系了主持人,但他们说他们“没有受过培训”来调试代码。我因错误而感到茫然。代码正常运行,它只是给出了这些错误。

1 个答案:

答案 0 :(得分:0)

每次运行此脚本时,您似乎都在检索超出需要的信息,然后放弃部分读取的结果集。每次只能处理三件物品。废弃的结果集对于数据库服务器来说并不是很好。

我建议您更改此查询:

SELECT * FROM mail WHERE status=false

SELECT * FROM mail WHERE status=false LIMIT 3

然后,我建议您按如下方式更改循环代码:

$count = 0;
while($row = mysqli_fetch_array($result)) {
    $count++;
    mysqli_query($con, "UPDATE mail SET status=true WHERE id='$row[id]'");
    mail($row['send_to'], $row['subject'], $row['message'], $row['headers']);
    mysqli_query($con, "DELETE FROM mail WHERE status=true AND id='$row[id]'");
}

mysqli_close($con);
if ($count > 0) {
   echo "exit";
}

似乎只有在结果集不为空时才需要使用echo命令,而这仍然是这样。但它始终会读取每个结果集。

此外,它不会获取超出您需要的行数,因此可能更有效。