[Typo3-dev] Howto safely increase DB value

Peter Russ peter.russ at 4many.net
Tue Mar 29 18:11:21 CEST 2005


Kraft Bernhard schrieb:

> Hallo list,
> 
> 
> In a site I have a selfmade FE-Plugin which needs to increase the value 
> of a DB-field (int)
> whenever the user clicks a link.
> 
> With simple SQL I would do it like:
> UPDATE mytable SET field=field+1 WHERE uid=123;
> 
> This ensures that if two instances of the programm execute the same SQL 
> query at almost the
> same time that the value gets increases 2 times.
> 
> However if i do:
> $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('field', 'mytable', 
> 'uid=123');
> $row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
> $GLOBALS['TYPO3_DB']->exec_UPDATEquery('mytable', 'uid=123', 
> array('field' => (intval($row['field'])+1)));
> 
> it is not safe that not at some time two script run, each one fetches 
> the actual value
> and then each script sets the resulting value to just one more than 
> before ...
> 
> 
> How to cope with this ?
> 
> The exec_UPDATEquery function can't get used for this ?
> 
> Will I have to use the "mysql" method and break DBAL compatibility (it 
> is not needed for this site
> as it will never run with another DB than mysql ... but I'm already 
> somehow used to the DBAL API calls)
> 
> 
> greets,
> Bernhard
Why not use DBAL _AND_ the sql_query method in one shot?
Then the DB would handle it:
$GLOBALS['TYPO3_DB']->sql_query('UPDATE '.$table.' SET field=field+1 
WHERE uid='.$uid);

Regs. Peter

-- 
_____________________________
4Many Services
http://www.4many.net              http://www.4dfx.de

Kundenserver/Customer server
http://www.typo3-server.net




More information about the TYPO3-dev mailing list