我在想如何检查我的记录是否存在运行原始SQL查询。我尝试使用is_null
函数,但它对我不起作用。因此,当我尝试选择错误的值并按下提交按钮时,它会在浏览器中返回“成功”纯文本。
public function readEmployeeRecords()
{
$users = DB::select('select * from users where username = ?', [1]);
if(is_null($users))
{
return ('Failed');
}
else
{
return('Success');
}
}
表格
<form class = "form-inline" role = "form" method = "post" action = "{{ route ('account.accountSearch') }}">
<div class = "form-group">
<input type = "text" name = "search" class = "form-control" placeholder = "Employee username">
</div>
<button type = "submit" class = "btn btn-default">Search</button>
<input type = "hidden" name = "_token" value = "{{ Session::token() }}">
</form>
答案 0 :(得分:0)
使用SELECT EXISTS( your subquery )
:
public function readEmployeeRecords()
{
$users = DB::select('SELECT EXISTS(SELECT * FROM users WHERE username = ?)', [1]);
if (!$users[0]) {
return ('Failed');
}
else {
return('Success');
}
}
我原来的答案是使用COUNT(*)
,这在逻辑上应该有效。但是,我怀疑是一个&#34;记录&#34;无论实际数量如何,总是被退回。
答案 1 :(得分:0)
Laravel 5.2 documentation表示“select方法将始终返回一组结果。”因此,您可以使用count()
查看数组中是否有任何结果:
public function readEmployeeRecords()
{
$users = DB::select('select * from users where username = ?', [1]);
if ( ! count($users)) {
return ('Failed');
}
return ('Success');
}
is_null()
检查变量是否为NULL
。空数组不等于NULL
答案 2 :(得分:-1)
尝试使用
if(is_null($ users)|| $ users =“”){