[英]how to use where like in restful api codeigniter 4?
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
我正在制作一个 reactjs,它使用 codeigniter 连接到宁静的 api 服务器 4. 我只想显示字段
username
和full_name
包含查询字符串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?当 react js 应用程序中的搜索框为空时,所有数据都正确显示。但是当搜索框不为空时,
$data
返回一个空数组group_start()
部分有问题吗? how should I fix this?我该如何解决这个问题?
thanks in advance提前致谢
The problem is, your not using any wild card in your SQL query this is a link to SQL like operation问题是,您在 SQL 查询中没有使用任何通配符,这是指向 SQL 之类操作的链接
also I don't think you don't need to pars query string from URL, just type $_GET['q']
我也不认为你不需要解析来自 URL 的查询字符串,只需键入
$_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.当您的查询中有 q 时,空条件为真。 just do it like blow:
就像打击一样:
$searchStr = $_GET['q'] ? $_GET['q'] : '' ;
sample: $myString = condition? true: false;
示例:
$myString = condition? true: false;
$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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.