gpt4 book ai didi

php - 带有 CodeIgniter 的 REST API

转载 作者:可可西里 更新时间:2023-11-01 13:30:48 24 4
gpt4 key购买 nike

我正在为我正在开发的移动应用程序创建网络服务后端。 (我是一名经验丰富的 Obj-C 开发人员,而不是网页设计师!)本质上我想使用 Codeigniter 和 Phil Sturgeon 的 RESTful API 服务器 https://github.com/philsturgeon/codeigniter-restserver但是,我在设置和工作时遇到了一些麻烦。

我有 MySQL 数据库,其中设置了数据。我需要一些帮助来编写一个 CodeIgniter PHP 模型和 Controller ,以返回该数据库中内容的 JSON 数据。我发现的所有教程和论坛帖子都处理 Controller 中的硬编码数据,而不是 MySQL 数据库。我希望 URL 的格式像这样 http://api.mysite.com/v1/search?id=1&name=foo&city=bar ,我可能有 50 多个参数要在 url 中传递。

使用 Phil 的代码,我想出了这个作为我的 Controller :

public function index_get()
{
if (!$this->get('id'))
{
$this->response(NULL, 400);
}

$data = $this->grid_m->get_id($this->get('id'));
if ($data)
{
$this->response($data, 200);
}
else
{
$this->response(NULL, 404);
}
}

这只会给我一个搜索词:id?=# ..我需要知道如何获得多个搜索词

这是我的 Codeigniter 模型:

<?php

class Grid_m extends CI_Model
{

function get_all()
{
$query = $this->db->get('grid');
if ($query->num_rows() > 0)
{
return $query->result();
}
return FALSE;;
}

无论我在 URL 中传递什么 id 或 url 术语,这只会返回我的 MySQL 数据库中的所有内容。

在开发我自己的自定义 API 时,我是一个大菜鸟,所以任何关于如何修复我的 Controller 和数据库模型的建议都会有很大的帮助!

感谢您的帮助!

-布赖恩

最佳答案

这是一个老问题,但如果有人到这里仍然需要帮助,请尝试以下代码:

在你的 Controller 中:

public function index_get()  
{
$where = '';

if ($this->get('id')) // search by id when id passed by
{
$where .= 'id = '.$this->get('id');
}

if ($this->get('name')) // add search by name when name passed by
{
$where .= (empty($where)? '' : ' or ')."name like '%".$this->get('name')."%'";
}

if ($this->get('city')) // add search by city when city passed by
{
$where .= (empty($where)? '' : ' or ')."city like '%".$this->get('city')."%'";
}

// you can add as many as search terms

if ( ! empty($where))
{
$data = $this->grid_m->get_searched($where);

if ($data)
{
$this->response($data, 200);
}
else
{
$this->response(NULL, 404);
}
}
else
{
$this->response(NULL, 404);
}
}

在您的模型中,创建 get_searched 函数:

class Grid_m extends CI_Model  
{
function get_searched($where = NULL)
{
if ( ! is_null($where))
{
$this->db->where($where);
$query = $this->db->get('grid');

if ($query->num_rows() > 0)
{
return $query->result();
}
}
return FALSE;
}
}

关于php - 带有 CodeIgniter 的 REST API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13549262/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com