note 76848 added to function.mysql-query

From: Date: Thu, 02 Aug 2007 01:13:51 +0000
Subject: note 76848 added to function.mysql-query
Groups: php.notes 
Request: Send a blank email to php-notes+get-129119@lists.php.net to get a copy of this message
Simulating an atomic operation for application locks using mysql. $link = mysql_connect('localhost', 'user', 'pass'); if (!$link) { die('Not connected : ' . mysql_error()); } // make foo the current db $db_selected = mysql_select_db('foo', $link); if (!$db_selected) { die ('Can\'t use foo : ' . mysql_error()); } $q = "update table set LOCK='F' where ID='1'"; $lock = mysql_affected_rows(); If we assume NOT LOCKED = "" (empty string) LOCKED = 'F' then if the column LOCK had a value other than F (normally should be an empty string) the update statement sets it to F and set the affected rows to 1. Which mean than we got the lock. If affected rows return 0 then the value of that column was already F and somebody else has the lock. The secret lies in the following statement taken from the mysql manual: "If you set a column to the value it currently has, MySQL notices this and does not update it." Of course all this is possible if the all application processes agree on the locking algorithm. ---- Server IP: 200.115.170.166 Probable Submitter: 201.227.214.4 ---- Manual Page -- http://www.php.net/manual/en/function.mysql-query.php Edit -- https://master.php.net/note/edit/76848 Del: integrated -- https://master.php.net/note/delete/76848/integrated Del: useless -- https://master.php.net/note/delete/76848/useless Del: bad code -- https://master.php.net/note/delete/76848/bad+code Del: spam -- https://master.php.net/note/delete/76848/spam Del: non-english -- https://master.php.net/note/delete/76848/non-english Del: in docs -- https://master.php.net/note/delete/76848/in+docs Del: other reasons-- https://master.php.net/note/delete/76848 Reject -- https://master.php.net/note/reject/76848 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#129119) next »