9951 explained code solutions for 126 technologies


predisHow do I use PHP and Redis together to create a transaction?


PHP and Redis can be used together to create a transaction by using the following steps:

  1. Establish a connection to the Redis server from PHP using a client library like Predis.
$redis = new Predis\Client();
  1. Use WATCH and MULTI/EXEC commands to create a transaction block.
$redis->watch('key1');
$redis->multi();
$redis->set('key1', 'value1');
$redis->set('key2', 'value2');
$redis->exec();
  1. Use DISCARD command to discard all the commands in the transaction block.
$redis->discard();
  1. Use UNWATCH command to unlock the keys that were being watched.
$redis->unwatch();
  1. Use EXISTS command to check if the keys have been set.
$redis->exists('key1'); // returns 1 if key exists

By following these steps, a transaction can be created using PHP and Redis.

Edit this code on GitHub