PHP Redis related operations collection
Connecting database
$redis = new Redis(); $redis->connect('127.0.0.1',6379);//链接redis服务 // 参数 // `host: string`,服务地址 // `port: int`,端口号 // `timeout: float`,链接时长 (可选, 默认为 0 ,不限链接时间) // 注: 在redis.conf中也有时间,默认为300 $redis->pconnect('127.0.0.1',6379);//不会主动关闭的链接 $redis->setOption();//设置redis模式 $redis->getOption();//查看redis设置的模式 $redis->ping();//查看连接状态
Basic operations
$redis->get('key');//得到某个key的值(string值),如果该key不存在,return false
$redis->set('key','value');//set 写入key 和 value(string值),如果写入成功,return ture
$redis->setex('key', 3600, 'value'); // setex 带生存时间的写入值
$redis->setnx('key', 'value');//判断是否重复的,写入值,如存在了不修改返回0,不存在就添加返回1
$redis->delete('key');//删除指定key的值
//返回已经删除key的个数(长整数)
$redis->delete('key1', 'key2');
$redis->delete(array('key3', 'key4', 'key5'));
$redis->ttl('key1');//查询生存时间,持久化的返回-1,有生存时间的返回时间(单位秒)
$redis->persist('key1');//移除生存时间到期的key,如果key到期 true 如果不到期 false
$redis->mset(array('key0' => 'value0', 'key1' => 'value1'));//(redis版本1.1以上才可以用),批量赋值
$redis->incr('key1');//key中的值进行自增1,如果填写了第二个参数,自增第二个参数所填的值
$redis->incrBy('key1', 10);
$redis->decr("key1"); //减少1
$redis->decrBy("key1",5) //减少5
//返回原来key中的值,并将value写入key
$redis->set('x', '42');
$redis->getSet('x', 'lol'); // return '42'
$newValue = $redis->get('x'); // return 'lol'
//名称为key的string的值在后面加上value
$redis->set('key', 'value1');
$redis->append('key', 'value2');
//返回名称为key的string中start至end之间的字符
$redis->set('key', 'string value');
$redis->getRange('key', 0, 5);
$redis->getRange('key', -5, -1);
//改变key的string中start至end之间的字符为value
$redis->set('key', 'Hello world');
$redis->setRange('key', 6, "redis");
$redis->get('key');list related operations
$redis->lpush('list','HHHHHHH');//返回链表的元素个数 $redi->lrange('list',0,-1); //返回全部数据,数组形式 $redis->lrange('list',0.2); //返回连表0-2坐标的三个元素 //lPushx/rPushx在名称为key的list左边(头)/右边(尾)添加一个值为value的元素,如果value已经存在,则不添加 $redis->lPushx(key, value); $redis->lpop('list');//输出链表最左边的key的值,输出后删除掉这个key $redis->rpop('list');//输出链表最右边的ksy的值,输出后删除掉这个key $redis->lset('list',7,"update"); //修改坐标为7的值,成功返回1
Collection:
sAdd无序集合 $redis->sAdd('s1','lisi'); $redis->sAdd('s1','wangwu'); $redis->sAdd('s1','77'); $redis->sAdd('t1','lisi'); $redis->sAdd('t1','wangwu'); $redis->sAdd('t1','66'); $redis->sMembers('s1');//s1的所有集合内容 $redis->sDiff('s1','t1');//s1有的,t1没有的,差集 $redis->sInter('s1','t1');//返回s1和t1两个集合都有的,数组形式 $redis->sCard('s1');//返回s1集合里面的个数,有多少个就返回多少个,没有从0开始的,坐标才从0开始的 $redis->sPop('s1');//抽奖场景,返回集合里面随机的数,默认返回1个,返回后就删除这个数,中奖了就不能再中了 $redis->sRandMember('s1');//随机返回集合里面的一个元素,但不删除,重复中奖 $i = $redis->sIsMember('s1','zhangsan2');//查询张三在不在集合里面,在1,不在false $redis->sInterStore('output', 'key1', 'key2', 'key3');//求交集并将交集保存到output的集合 $redis->sDiffStore('output', 'key1', 'key2', 'key3');//求差集并将差集保存到output的集合
zAdd ordered collection
$redis->zAdd('y1',1,'zhangsan'); $redis->zAdd('y1',2,'lisi'); $redis->zAdd('y1',3,'wangwu'); $redis->zRange('y1',0,-1);//排序,根据插入的时候的排序从小到大 $redis->zRevRange('y1',0,-1);//反转排序,插入的时候键值越高,排序越优先 $redis->zDelete('y1', 'wangwu');//删除集合中指定数据 $redis->zSize('y1');//返回名称为y1的zset的所有元素的个数 $redis->zRemRangeByScore('key', 1, -1);//删除名称为key的zset中score >= star且score <= end的所有元素,返回删除个数 $redis->zCard('y1');//获取有序集合里面的个数,有多少个就返回多少个,没有从0开始的,坐标才从0开始的.无序就scard,有序就zcard,有z没有s $redis->zCount(key, star, end);//返回名称为key的zset中score >= star且score <= end的所有元素的个数 $redis->zRangeByScore(key, star, end, array(withscores, limit ));//返回名称为key的zset中score >= star且score <= end的所有元素 $redis->zScore(key, val2);//返回名称为key的zset中元素val2的score //返回名称为key的zset(元素已按score从小到大排序)中val元素的rank(即index,从0开始),若没有val元素,返回“null”。zRevRank 是从大到小排序 $redis->zRevRank(key, val); //如果在名称为key的zset中已经存在元素member,则该元素的score增加increment;否则向集合中添加该元素,其score的值为increment $redis->zIncrBy('key', increment, 'member');
Hash operation
$redis->hSet('h', 'key1', 'hello');//向名称为h的hash中添加元素key1—>hello $redis->hGet('h', 'key1');//返回名称为h的hash中key1对应的value(hello) $redis->hLen('h');//返回名称为h的hash中元素个数 $redis->hDel('h', 'key1');//删除名称为h的hash中键为key1的域 $redis->hKeys('h');//返回名称为key的hash中所有键 $redis->hVals('h');//返回名称为h的hash中所有键对应的value $redis->hGetAll('h');//返回名称为h的hash中所有的键(field)及其对应的value $redis->hExists('h', 'a');//名称为h的hash中是否存在键名字为a的域 $redis->hIncrBy('h', 'x', 2);//将名称为h的hash中x的value增加2 $redis->hMset('user:1', array('name' => 'Joe', 'salary' => 2000));//向名称为key的hash中批量添加元素 $redis->hmGet('h', array('field1', 'field2'));//返回名称为h的hash中field1,field2对应的value
redis operation related
$redis->flushDB();//清空当前数据库 $redis->flushAll();//清空所有数据库 $redis->randomKey();//随机返回key空间的一个key $redis->select();//选择一个数据库 $redis->move();//转移一个key到另外一个数据库 $redis->select(0); // switch to DB 0 $redis->set('x', '42'); // write 42 to x $redis->move('x', 1); // move to DB 1 $redis->select(1); // switch to DB 1 $redis->get('x'); // will return 42 $redis->rename('x', 'y');//给key重命名,也可写 renameKey() $redis->renameNx();//与remane类似,但是,如果重新命名的名字已经存在,不会替换成功 $redis->setTimeout('x', 3);//设定一个key的活动时间(s),等同expire() $redis->expireAt('x', time() + 3);//key存活到一个unix时间戳时间 $redis->keys('user*');//返回满足给定pattern的所有key,等同getKeys $redis->dbSize();//查看现在数据库有多少key $redis->auth('foobared');//密码认证 $redis->bgrewriteaof();//使用aof来进行数据库持久化 $redis->slaveof('10.0.1.7', 6379);//选择从服务器 $redis->save();//将数据同步保存到磁盘 $redis->bgsave();//将数据异步保存到磁盘 $redis->lastSave();//返回上次成功将数据保存到磁盘的Unix时戳 $redis->info();//返回redis的版本信息等详情 $redis->exists('key');//判断key是否存在。存在 true 不在 false $redis->sUnion('s0', 's1', 's2');//求并集,s0,s1,s2 同时求并集 $redis->sUnionStore('output', 'key1', 'key2', 'key3');//求并集并将并集保存到output的集合 $redis->sort();//排序,分页等 // 参数 // 'by' => 'some_pattern_*', // 'limit' => array(0, 1), // 'get' => 'some_other_pattern_*' or an array of patterns, // 'sort' => 'asc' or 'desc', // 'alpha' => TRUE, // 'store' => 'external-key' //例 $redis->sadd('s', 5); $redis->sadd('s', 4); $redis->sadd('s', 2); $redis->sadd('s', 1); $redis->sadd('s', 3); var_dump($redis->sort('s')); // 1,2,3,4,5 var_dump($redis->sort('s', array('sort' => 'desc'))); // 5,4,3,2,1 var_dump($redis->sort('s', array('sort' => 'desc', 'store' => 'out'))); // (int)5 $redis->strlen('key');//得到key的string的长度 $redis->getBit()//用于对 key 所储存的字符串值,获取指定偏移量上的位(bit)。 $redis->setBit()//用于对 key 所储存的字符串值,设置或清除指定偏移量上的位(bit)。
For more PHP related knowledge, please visit PHP tutorial!
The above is the detailed content of A complete list of PHP Redis related operations. For more information, please follow other related articles on the PHP Chinese website!
PHP: An Introduction to the Server-Side Scripting LanguageApr 16, 2025 am 12:18 AMPHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.
PHP and the Web: Exploring its Long-Term ImpactApr 16, 2025 am 12:17 AMPHP has shaped the network over the past few decades and will continue to play an important role in web development. 1) PHP originated in 1994 and has become the first choice for developers due to its ease of use and seamless integration with MySQL. 2) Its core functions include generating dynamic content and integrating with the database, allowing the website to be updated in real time and displayed in personalized manner. 3) The wide application and ecosystem of PHP have driven its long-term impact, but it also faces version updates and security challenges. 4) Performance improvements in recent years, such as the release of PHP7, enable it to compete with modern languages. 5) In the future, PHP needs to deal with new challenges such as containerization and microservices, but its flexibility and active community make it adaptable.
Why Use PHP? Advantages and Benefits ExplainedApr 16, 2025 am 12:16 AMThe core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.
Debunking the Myths: Is PHP Really a Dead Language?Apr 16, 2025 am 12:15 AMPHP is not dead. 1) The PHP community actively solves performance and security issues, and PHP7.x improves performance. 2) PHP is suitable for modern web development and is widely used in large websites. 3) PHP is easy to learn and the server performs well, but the type system is not as strict as static languages. 4) PHP is still important in the fields of content management and e-commerce, and the ecosystem continues to evolve. 5) Optimize performance through OPcache and APC, and use OOP and design patterns to improve code quality.
The PHP vs. Python Debate: Which is Better?Apr 16, 2025 am 12:03 AMPHP and Python have their own advantages and disadvantages, and the choice depends on the project requirements. 1) PHP is suitable for web development, easy to learn, rich community resources, but the syntax is not modern enough, and performance and security need to be paid attention to. 2) Python is suitable for data science and machine learning, with concise syntax and easy to learn, but there are bottlenecks in execution speed and memory management.
PHP's Purpose: Building Dynamic WebsitesApr 15, 2025 am 12:18 AMPHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.
PHP: Handling Databases and Server-Side LogicApr 15, 2025 am 12:15 AMPHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.
How do you prevent SQL Injection in PHP? (Prepared statements, PDO)Apr 15, 2025 am 12:15 AMUsing preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Linux new version
SublimeText3 Linux latest version

Dreamweaver CS6
Visual web development tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.






