[英]Method to check record exist in database, and then if true return record in CakePHP?
[英]How to check if record exist in database
我在想如何检查我的记录是否存在运行原始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>
使用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(*)
,从逻辑上讲应该可以使用。 但是,我怀疑无论实际计数如何,总会返回一条“记录”。
Laravel 5.2文档说:“ 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
尝试使用
if(is_null($ users)|| $ users =“”){
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.