dongpang1898 2012-08-16 04:18
浏览 36

PHP +锁定MySQL表失败

I have a table that needs to be locked from being inserted but it also needs to be able to be updated while inserts are prevented.

function myfunction() {
  $locked = mysql_result(mysql_query("SELECT locked FROM mylock"),0,0);
  if ( $locked ) return false;
  mysql_query("LOCK TABLES mylock WRITE");
  mysql_query("UPDATE mylock SET locked=1");
  mysql_query("UNLOCK TABLES");

  /* I'm checking another table to see if a record doesn't exist already */
  /* If it doesn't exist then I'm inserting that record */

  mysql_query("LOCK TABLES mylock WRITE");
  mysql_query("UPDATE mylock SET locked=0");
  mysql_query("UNLOCK TABLES");  
}

But this isn't enough, the function is called again from another script and simultaneously inserts are happening from the 2 calls to the function, and I can't have that because it's causing duplicate records.

This is urgent please help. I thought of using UNIQUE on the fields but there are 2 fields (player1, player2), and NEITHER cannot contain a duplicate of a player ID.

Unwanted behavior: Record A = ( Player1: 123 Player2: 456 ) Record B = ( Player1: 456 Player2: 123 )

  • 写回答

3条回答 默认 最新

  • dongmufen8105 2012-08-16 04:29
    关注

    I suggest not using locks at all. Instead, when insterting the data, do like this:

    mysql_query("INSERT IGNORE INTO my_table VALUES(<some values here>)");
    if(mysql_affected_rows()>0)
    {
        // the data was inserted without error
        $last_id = mysql_insert_id();
        // add what you need here
    }
    else
    {
        // the data could not be inserted (because it already exists in the table)
        // query the table to retrieve the data
        mysql_query("SELECT * FROM my_table WHERE <some_condition>");
        // add what you need here
    }
    

    When adding the IGNORE keyword to an INSERT statement, MySQL will attempt to insert the data. If it doesn't work because a record with the same primary key is already in the table, it will fail silently. mysql_affected_rows is used to know the number of inserted records and decide what to do.

    评论

报告相同问题?

悬赏问题

  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)