Php Larvel:检查MySQL查询是否有结果
第一个拉威尔项目。我有一个控制器功能,可以检查是否有带有条形码的记录。如果没有,请插入一条记录。如果是,则为计数添加一个Php Larvel:检查MySQL查询是否有结果,php,mysql,laravel,laravel-5,Php,Mysql,Laravel,Laravel 5,第一个拉威尔项目。我有一个控制器功能,可以检查是否有带有条形码的记录。如果没有,请插入一条记录。如果是,则为计数添加一个 public function sellmode(Request $request){ $barcode=$request->barcode; $test = DB::select('select count from sellmode where barcode = ?', [$barcode]); $row_cnt = mysqli_num_
public function sellmode(Request $request){
$barcode=$request->barcode;
$test = DB::select('select count from sellmode where barcode = ?', [$barcode]);
$row_cnt = mysqli_num_rows($test);
if ($row_cnt == 0) {
Debugbar::info('Új sor');
DB::insert('insert into sellmode (barcode, count) VALUES (?, ?)', [$barcode, '1']);
} else {
Debugbar::info('Meglévő frissítése');
DB::update('update sellmode set count = count + 1 WHERE barcode = ?' [$barcode]);
}
return view(sell);
}
当我尝试它时,它出现了以下错误:
SellController.php第17行中的ErrorException:mysqli_num_rows()
期望参数1是给定数组的mysqli_结果
我做错了什么?在Laravel查询生成器上,你不能只是
mysql\u num\u rows
。Laravel查询生成器将返回一个,因此您可以使用该函数来确定它是否有任何结果
if ($test->isEmpty()) {
Debugbar::info('Új sor');
DB::insert('insert into sellmode (barcode, count) VALUES (?, ?)', [$barcode, '1']);
} else {
Debugbar::info('Meglévő frissítése');
DB::update('update sellmode set count = count + 1 WHERE barcode = ?' [$barcode]);
}
如果您使用的是Laravel 5.3之前的版本,查询生成器将返回一个数组。在本例中,您可以在此数组上使用php函数来了解返回了多少行
if (count($test) === 0) {
Debugbar::info('Új sor');
DB::insert('insert into sellmode (barcode, count) VALUES (?, ?)', [$barcode, '1']);
} else {
Debugbar::info('Meglévő frissítése');
DB::update('update sellmode set count = count + 1 WHERE barcode = ?' [$barcode]);
}
最好创建一个模型并使用它来查询数据库。也许是这样(在我看来更容易):
当我使用
test->isEmpty()
未定义的偏移量:0
因此,我最终使用它来检查DB::select中的空返回值:
$test = DB::select('select count from sellmode where barcode = ?', [$barcode]);
if(collect($test)->first()) {
// ...
} else {
$response = new \stdClass();
$response->error = true;
$response->message = 'Sellmode not found';
return response(json_encode($response))->header('Content-Type','application/json');
}
您不应该在这里使用mysqli\u num\u rows
或任何与mysqli相关的函数。拉威尔使用PDO。不过,出于参数的考虑,如果您想查看返回了多少行,您可以只计算结果数组中的值数<代码>$row\U cnt=计数($test)代码>谢谢,但我遇到了另一个错误:“SellController.php第17行中的FatalThrowableError:调用数组上的成员函数isEmpty()”在这种情况下,您可能使用的是低于5.3的Laravel版本。我已经用这些版本的解决方案更新了我的答案。我原以为我使用的是5.3,但现在我运行了“php artisan--version”,结果是“Laravel Framework 5.4.13”。我也尝试了第二个命令,“新行”正在工作,但“更新”的输出是以下错误消息:SQLSTATE[42000]:语法错误或访问冲突:1064您的SQL语法有错误;查看与您的MySQL服务器版本对应的手册,了解第1行“o”附近使用的正确语法(SQL:o)。不知道您使用的是哪个版本,但请查看文档:
$test = DB::select('select count from sellmode where barcode = ?', [$barcode]);
if(collect($test)->first()) {
// ...
} else {
$response = new \stdClass();
$response->error = true;
$response->message = 'Sellmode not found';
return response(json_encode($response))->header('Content-Type','application/json');
}