Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: Check if MySQL query has result

First Laravel project. I have a controllerfunction what checks if there any record with that barcode. If no insert a record. If yes add one for the count.

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);

}

When I tried it, it had the following error:

ErrorException in SellController.php line 17: mysqli_num_rows() expects parameter 1 to be mysqli_result, array given

What did I wrong?

like image 861
Feralheart Avatar asked Dec 06 '22 15:12

Feralheart


1 Answers

You can't just just mysql_num_rows on a Laravel query builder. Laravel query builder will return a collection, so you can just use the isEmpty function to find out if it has any results.

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]);
}

If you are using a Laravel version pre-5.3, the query builder will return an array. In this case, you can use the php count function on this array to know how many rows are returned

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]);
}
like image 150
Jerodev Avatar answered Dec 15 '22 21:12

Jerodev