【问题标题】:How to get value an array laravel 4?如何获取数组 laravel 4 的值?
【发布时间】:2013-09-04 06:00:21
【问题描述】:

我就是想问一下,用 laravel 4 怎么获取这段代码的值?

$auth = DB::select(
    'SELECT auth FROM users WHERE username like ?'
    , array($username)
);

当我显示代码的结果时,它会回显“数组”并且它总是将用户重定向到“另一个页面”,我实际上是在这样做:

if (Auth::attempt($userdata))
{
    if ($auth==0)
    {
        return Redirect::to('home');
    }
    elseif ($auth==1)
    {
        return Redirect::to('dashboard');
    } 
    else 
    {
        return Redirect::to('anotherpage');
    }
}

请帮忙。先感谢您。

【问题讨论】:

  • 要求代码的问题必须表明对正在解决的问题有最低限度的了解。包括尝试过的解决方案、它们为什么不起作用以及预期结果。另见:Stack Overflow question checklist
  • 这很可能不是 Laravel-4 特有的。请更具体地说明您的问题到底出在哪里。 此代码的值是什么?

标签: php laravel laravel-4 eloquent


【解决方案1】:

首先,为什么要通过 Auth 类和手动 SELECT 查询对用户进行两次身份验证? Auth::attempt 就够了。 Read it here.

无论如何,假设您真的想这样做,您的代码无法正常工作,因为您在 if 语句中将 $auth 分配为 0;所以这个:

if($auth = 0)   

基本上是这样的:

if(0) //Which is always false

所以,我将 if 语句更改为:

if($auth == 0)  

您的最终代码应该如下所示:

if(Auth::attempt($userdata)) 
{
  $auth = DB::table('users')->where('username', '=', $username)->first()->auth;//Don't use "LIKE" as it may cause huge security issues.
  if($auth == 0) {
        return Redirect::to('home');
  }
  else if($auth == 1) {
        return Redirect::to('dashboard');
  }
  else {
        return Redirect::to('anotherpage');
  }
}

【讨论】:

  • 我正在尝试获取登录用户的“Auth”列的值。例如,当用户登录时。它将首先进行身份验证,然后告诉用户将去哪个页面使用if($auth==0
【解决方案2】:

当您尝试回显数组时会发生这种情况。请改用print_r()。它打印出数组(或变量)内容的可读输出:

$myArray = DB::select('SELECT auth FROM users WHERE username like ?', array($username));
print_r($myArray);

这样,您将看到数组的内容,然后可以显示特定项目。

将其包含在<pre> 标签中将使输出更具可读性:

echo '<pre>';
print_r($myArray);
echo '</pre>';

或者简单地说:

echo '<pre>', print_r($myArray), '</pre>';

【讨论】:

  • 这行得通,但是当我把它放在 if 语句中时它不起作用,先生。
【解决方案3】:

您使用的查询生成器错误。试试这个:

$auth = DB::table('users')->select('auth')->where('username', 'LIKE', $username)->get();
dd($auth);

【讨论】:

    猜你喜欢
    • 2013-02-02
    • 1970-01-01
    • 2015-07-08
    • 2019-06-22
    • 2015-01-28
    • 2018-08-09
    • 2020-02-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多