【问题标题】:how to get a value of id from database table in cakephp如何从cakephp中的数据库表中获取id的值
【发布时间】:2016-04-05 20:22:03
【问题描述】:

CAKEPHP

我无法从表中获取 id 值

我的表名为"users",id 为PK(int),username(txt) name(txt)

我试过了

$this->users->read('users.id)

获取用户ID但不起作用。

我也试过了

$this->request->session()->read('users.id')

我想做一个像

这样的条件
if($this->users->read('users.id'))==1 

因为我想对其他 id 的用户隐藏 html 代码。 我也尝试使用类似的东西.....read('users.username')=='admin'但他们也不会工作

如您所见,尝试使用 session() 获取 id 但不起作用

我的登录功能是

public function login()
{
    if ($this->request->is('post')) {
        $user = $this->Auth->identify();
        if ($user) {

                $this->Auth->setUser($user);
            return $this->redirect(['controller'=>'Accounts']);
        }
        $this->Flash->error('blalalalala');
    }
}

这是我上学的第一个 cakephp 项目,你们能帮帮我吗? :) 我在 php 中很弱


感谢提示,但仍然不起作用。

我用这个

$id  =  $this->Auth->user('id');  // To get user id 
    $this->set('id', $id);

在过滤器之前的功能中的我的 AppController 中。

我使用例如if($id==1) .....但仍然无法正常工作。 var dump 显示为 null。

我忘了说,但我有CakePHP 3x version

【问题讨论】:

  • 我不知道您是如何学习其他语言或框架的,如果您在那里也尝试过“反复试验”,那一定是一段痛苦而漫长而艰苦的经历。所以我建议你先做基础教程,然后是官方文档的 Auth 教程:book.cakephp.org 它将给你一个适当的框架介绍并解决你的 auth 相关问题。

标签: php mysql cakephp cakephp-3.x


【解决方案1】:

要在控制器中设置用户任何信息,您可以使用

$this->Auth->user('fieldName');

AppControllerbeforeFilter方法中设置你需要的用户信息,如下代码

$id  =  $this->Auth->user('id');  // To get user id 
        $this->set('id', $id);   

现在在任何视图中,您都可以应用条件,例如

if($id==1) 
--do this-- 

如果你想在任何可以使用的地方获取用户 ID,在 cakephp 3.x 中是不允许的

AuthComponent::user('id')

详情可以看doc

【讨论】:

  • 应该注意,后一种方法在 CakePHP 3.x 中不再适用,问题可能是关于这个(在 CakePHP 2.x 中没有没有参数的AuthComponent::identify())。
  • 感谢@ndm 提供丰富的评论。我编辑了我的答案。
【解决方案2】:

你可以试试这些:

 $this->Auth->user('id'); // for controller action

$this->Session->read('Auth.User.id'); // for controller and views

AuthComponent::user('id') // anywhere 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-30
    • 2019-12-03
    • 2017-12-24
    • 1970-01-01
    • 2011-07-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多