【问题标题】:Count from database and show output从数据库中计数并显示输出
【发布时间】:2021-12-06 06:33:25
【问题描述】:

我想计算数据库中的用户 ID 并将总计数显示为输出,但出现错误。我使用以下代码:

//控制器代码

public function nsure(){
$users = DB::table('users')->count();
return view('nsure',compact(['users']));
}

//刀片视图代码

@foreach ($users as $user)
    <span class="" style="color:black;  font-size: 14px">{{$user->id }}</span>
@endforeach

【问题讨论】:

  • 您想在哪里显示计数以及在哪里出现错误?
  • get an error... 总是告诉我们确切的错误是什么。这比让人们猜测容易。幸运的是,在这种情况下它并不复杂,但并不总是那么简单。

标签: php mysql laravel


【解决方案1】:

显示所有用户 ID:

控制器

$users = DB::table('users')->get();

刀片

@foreach ($users as $user)
    <span class="" style="color:black;  font-size: 14px">{{$user->id}}</span>
@endforeach

显示所有用户的总数

控制器

$userCount = DB::table('users')->count();

刀片

<span class="" style="color:black;  font-size: 14px">{{$userCount}}</span>

【讨论】:

  • 它在显示所有用户时有效,但当我尝试计算总数时会低于错误。 "未定义变量 $userCount"
  • 确保将$userCount 添加到您的契约中:return view('nsure', compact('users', 'userCount'));
  • 现在可以正常使用了,谢谢。如果我写 $userCount = DB::select('select COUNT(id) as COUNT from users');而不是 $userCount = DB::table('users')->count();为什么它不起作用?
【解决方案2】:

$users = DB::table('users')-&gt;count();,$users是整数,不能迭代。

【讨论】:

  • 那么我应该怎么做才能解决这个问题?我的表名是 users。
  • 在输出用户数的同时要输出用户信息吗?
  • 不,我只想将用户总数作为输出,不需要任何信息。
  • @AbdullahALSamir 那么你为什么要编写将其视为用户列表并尝试打印每个用户的 ID 的代码?如果您只想回显计数,则只需回显计数...
猜你喜欢
  • 1970-01-01
  • 2017-09-16
  • 2019-08-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多