laravel使用Redis增删改查

文章描述:

laravel8使用Redis添加、删除、修改、读取操作

添加

$time = time();

$uid = Redis::incr('userid');   // 名称为key的string增1操作
// 添加
Redis::hmset('user:'.$uid, array('uid' => $uid,'name'=>'123', 'time' => $time));

读取

$data = array();
for( $i = 1; $i <= Redis::get('userid'); $i++ ){

     $data[] = Redis::hgetall('user:'.$i);

     //过滤数组中的空元素

     $data = array_filter($data);

}
//   echo "<pre>";
//   print_r($data);

return View::make('demo',['data'=>$data]);

列表模板

<table border="1" cellspacing="0" cellpadding="5">
    @if($data)
        @foreach($data as $v)
            <tr>
                <td>{{$v['uid']}}</td>
                <td>{{$v['name']}}</td>
                <td>{{$v['time']}}</td>
                <td>
                    <a href="{{ URL::to('test/input') }}?id={{$v['uid']}}">编辑</a>
                    |
                    <a href="{{URL::to('test/del')}}?id={{$v['uid']}}">删除</a>
                </td>
            </tr>


        @endforeach
    @endif
</table>

编辑

public function edit(){
        print_r($_POST);
        $uid = $_POST['id'];
        $name = $_POST['name'];
        $time = $_POST['time'];
        $res = Redis::hmset('user:'.$uid, array('name'=>$name, 'time'=>$time));
}
// 编辑框
public function input(){
        $uid =  $_GET['id'];
        $data = Redis::hgetall('user:'.$uid);
//        print_r($data);
        return View::make('input',['data'=>$data]);
}

模板

<form action="{{ URL::to('test/edit') }}" method="post">
    @csrf
<table>
    <tr>
        <td>姓名:</td>
        <td>
            <input type="text" name="name" value="{{$data['name']}}" />
        </td>
    </tr>
    <tr>
        <td>
            时间:
        </td>
        <td>
            <input type="text" name="time" value="{{$data['time']}}"/>
        </td>
    </tr>
    <tr>
        <td>
            <input type="hidden" name="id" value="{{$data['uid']}}" />
            <input type="submit" value="submit" />
        </td>
    </tr>
</table>
</form>

删除

// 删除
public function del(){
        $uid = $_GET['id'];
        Redis::del('user:'.$uid);
}

 

发布时间:2023/04/30

发表评论