Home > Net >  how to use where like in restful api codeigniter 4?
how to use where like in restful api codeigniter 4?

Time:03-30

I'm making a reactjs that is connected to a restful api server using codeigniter 4. I want to only show the data where the field username and full_name contains a query string q

this is how my code looks like more or less:

<?php
namespace App\Controllers;

use CodeIgniter\RESTful\ResourceController;
use CodeIgniter\API\ResponseTrait;
use App\Models\UserModel;

class Users extends ResourceController
{
    use ResponseTrait;

    public function index()
    {
        $model = new UserModel();

        $data = [];

        // example uri: http://localhost:8080/users?q=asd
        $qs = $_SERVER['QUERY_STRING'];
        parse_str($_SERVER['QUERY_STRING'], $_GET);
        $searchStr = empty($_GET['q']) ? '' : $_GET['q'];
        if ($searchStr)
        {
            $data = $model->group_start()
                            ->like('username', $searchStr)
                            ->or_like('nama', $searchStr)
                        ->group_end()
                        ->findAll();
        }
        else
        {
            $data = $model->findAll();
        }

        return $this->respond($data);
    }
}

when the search box in the react js app is empty, all the data is being shown correctly.. but when the search box is not empty, the $data returns an empty array.. is the problem around the group_start() part? how should I fix this?

thanks in advance

CodePudding user response:

The problem is , your not using any wild card in your SQL query this is a link to SQL like operation

also I don't think you don't need to pars query string from URL , just type $_GET['q']

in this line u had a mistake to :

$searchStr = empty($_GET['q']) ? '' : $_GET['q']);

the empty condition is true when u have q in your query . just do it like blow :

$searchStr = $_GET['q'] ? $_GET['q'] : '' ;

sample : $myString = condition ? true : false ;

here is how I don it : Pay attention to the pattern line

public function index()
    {
        $model = new UserModel();
        $data = [];
        $searchStr = $_GET['q'] ? $_GET['q'] : '' ;
        if ($searchStr)
        {
            $patern = '%'.$searchStr.'%'; // % char represent any char in before and after

            $data = $model->group_start()
                            ->like('username', $patern )
                            ->or_like('nama', $patern )
                        ->group_end()
                        ->findAll();
        }
        else
        {
            $data = $model->findAll();
        }
  • Related