[英]How to check if record exist in database
I'm thinking how can I check if I my record exists running raw SQL queries. 我在想如何检查我的记录是否存在运行原始SQL查询。 I tried to use
is_null
function but it doesn't work for me. 我尝试使用
is_null
函数,但对我不起作用。 So when I try to select wrong values and hitting the submit button it return me the 'Success' plain text in the browser. 因此,当我尝试选择错误的值并单击“提交”按钮时,它将在浏览器中返回“成功”纯文本。
public function readEmployeeRecords()
{
$users = DB::select('select * from users where username = ?', [1]);
if(is_null($users))
{
return ('Failed');
}
else
{
return('Success');
}
}
Form 形成
<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>
Use SELECT EXISTS( your subquery )
: 使用
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');
}
}
My original answer was using COUNT(*)
, which logically should have worked. 我最初的答案是使用
COUNT(*)
,从逻辑上讲应该可以使用。 However, I suspect th0at one "record" was always being returned, regardless of the actual count. 但是,我怀疑无论实际计数如何,总会返回一条“记录”。
The Laravel 5.2 documentation says "The select method will always return an array of results." Laravel 5.2文档说:“ select方法将始终返回结果数组。” So you could use
count()
to see if there are any results in the array: 因此,您可以使用
count()
来查看数组中是否有任何结果:
public function readEmployeeRecords()
{
$users = DB::select('select * from users where username = ?', [1]);
if ( ! count($users)) {
return ('Failed');
}
return ('Success');
}
is_null()
checks if a variable is NULL
. is_null()
检查变量是否为NULL
。 An empty array is not equal to NULL
空数组不等于
NULL
Try using 尝试使用
if(is_null($users) || $users = "") { if(is_null($ users)|| $ users =“”){
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.