5

I have a php page that needs to write to a database sometimes at the beginning of the script.

During a scheduled mysqldump backup, the page isn't accessible, because it is trying to write to a table that is locked.

During the lock, MySql queues those sql updates, and after the backup is complete, they do get executed as desired. Yet my php page won't display until the backup is complete.

However, since the updates do not return anything to the script, I wish they wouldn't hang up my script during the lock; I hope there's a way I can tell php to just send the sql update to mysql and don't worry about confirmation that the update completed.

I want php to send the query to mysql, and then just continue on to the next line of php if the update doesn't complete in one second.

I'm running php on a windows server, so I understand that some type of threading is not an option.

If there is way to set a timeout on that query (specifically), that might be ideal, but I don't want to renege the sql update altogether if it times out. I still want MySQL to process it after the lock is gone.

What would you recommend (given that removing the sql updates altogether is not an option)?

4

3 回答 3

3

一种解决方案,使用 PDO,开始一个超时连接,开始一个事务并且如果你有锁,超时将关闭连接并回滚。

对于 PDO 中的超时,使用 PDO::ATTR_TIMEOUT 。

于 2012-06-09T05:21:13.323 回答
3

对于可能遇到此线程的其他人,我最终编写了此函数来检测表是否已锁定,并且仅在未锁定时才进行 SQL更新

function isLocked($databaseName,$tableName)
    {
        $sql = "show open tables from `".$databaseName."` where `table`=`".tableName."` and In_use > 0;";
        $result = @mysql_query($sql);
        if (mysql_num_rows($result) != 0 )
        {
            return true;
        }
        else
        {
            return false;
        }
    }

(注意:此函数假设数据库连接已经建立)

这是可行的,因为我已经修改了代码,以便在下次加载页面时最终完成 sql 更新,而无需锁定到位。

于 2012-06-09T07:21:07.223 回答
1

我认为这样做的唯一方法是将脚本分成几部分并使用 ajax 调用,如果所有脚本都依赖于结果,则可以发送大更新并继续执行不依赖于该过程的脚本的其余部分的更新,唯一的办法是做一个很好的加载...

于 2012-06-09T05:21:39.090 回答