I'm working with codeigniter REST API. In my API call i'm trying to get value from $this->input->get('id') but does not get any value from the get.
public function data_get($id_param = NULL){
$id = $this->input->get('id');
if($id===NULL){
$id = $id_param;
}
if ($id === NULL)
{
$data = $this->Make_model->read($id);
if ($data)
{
$this->response($data, REST_Controller::HTTP_OK);
}
else
{
$this->response([
'status' => FALSE,
'error' => 'No record found'
], REST_Controller::HTTP_NOT_FOUND);
}
}
$data = $this->Make_model->read($id);
if ($data)
{
$this->set_response($data, REST_Controller::HTTP_OK);
}
else
{
$this->set_response([
'status' => FALSE,
'error' => 'Record could not be found'
], REST_Controller::HTTP_NOT_FOUND);
}
}
In the above code $id doesn't return any value.
Hope this will help you :
Use either $this->input->get('id') or $this->get('id') both should work
Your data_get method should be like this :
public function data_get($id_param = NULL)
{
$id = ! empty($id_param) ? $id_param : $this->input->get('id');
/*
u can also use this
$id = ! empty($id_param) ? $id_param : $this->get('id');
*/
if ($id)
{
$data = $this->Make_model->read($id);
if ($data)
{
$this->response($data, REST_Controller::HTTP_OK);
}
else
{
$this->response([
'status' => FALSE,
'error' => 'No record found'
], REST_Controller::HTTP_NOT_FOUND);
}
}
else
{
$this->response([
'status' => FALSE,
'error' => 'No id is found'
], REST_Controller::HTTP_NOT_FOUND);
}
}
Please change your code from $id = $this->input->get('id'); to $id = $this->get('id');
This should solve your problem.
Related
I'm having a problem getting errors from the Rest API I created with codeigniter 3, or rather using the library from "https://github.com/chriskacerguis/codeigniter-restserver".
This problem occurs when I POST data to server via API.
When I try to post the same data as the data in the database. it will issue an error message data already exists. with status 409.
but I didn't get the error in the client application that I made. only displays "Null"
https://localhost/server/api/room
public function index_post()
{
try {
$input = json_decode(file_get_contents('php://input'), true);
if (empty($input['noroom'])) {
throw new Exception('Error: field not found, field must be named noroom');
return false;
}
$exists = $this->Roommodel->findRoomByNoroomAndHotel($input['noroom'], $input['hotel_code'])->num_rows();
if ($exists > 0) {
$message = [
'status' => 409,
'message' => 'Data already exists',
];
$this->response($message, REST_Controller::HTTP_CONFLICT);
} else {
$dataRoom = [
'hotel_code' => $input['hotel_code'],
'noroom' => $input['noroom'],
'room_type' => $input['room_type'],
'room_area' => $input['room_area'],
'description' => $input['description'],
];
$insert = $this->Roommodel->save($dataRoom);
if ($insert) {
$data = [
'hotel_code' => $input['hotel_code'],
'noroom' => $input['noroom'],
'room_type' => $input['room_type'],
'room_area' => $input['room_area'],
'description' => $input['description'],
'message' => 'Success created data'
];
$message = [
'status' => 200,
'message' => 'Success',
'data' => $data,
];
$this->response($message, REST_Controller::HTTP_OK);
} else {
$message = [
'status' => 400,
'message' => 'Bad Request'
];
$this->response($message, REST_Controller::HTTP_BAD_REQUEST);
}
}
} catch (Exception $e) {
$message = [
'status' => 500,
'message' => $e->getMessage()
];
$this->response($message, REST_Controller::HTTP_INTERNAL_SERVER_ERROR);
}
}
below is my coding on the client side, and I try to do var_dum() the result is "Null" when there is an error.
when I tried insomia, I got the error message.
var $API = "";
function __construct()
{
parent::__construct();
$this->API = "http://localhost/server";
$this->load->library('session');
$this->load->library('curl');
$this->load->helper('form');
$this->load->helper('url');
}
public function create()
{
if ($this->input->is_ajax_request()) {
$data = [
'hotel_code' => $this->input->post('hotel_code'),
'noroom' => $this->input->post('noroom'),
'room_type' => $this->input->post('room_type'),
'room_area' => $this->input->post('room_area'),
'description' => $this->input->post('description'),
];
$response = json_decode($this->curl->simple_post($this->API . '/api/room', json_encode($data), array(CURLOPT_BUFFERSIZE => 10)), true);
var_dump($response); die();
echo json_encode($response);
} else {
show_404();
}
}
if the post data is successful, it will send the success message. and managed to get the message.
please help me to solve this problem
I have a function like below. It return array value and boolean value so i want to know how to define function return type? what is the return type of this function?
public function alert($id): ____ //this place value?
{
$model = Model::find($id);
if ($model) {
if ($model->status != 1) {
return array(
'header' => 'Failed',
'message' => 'Failed related message'
);
} else {
return array(
'header' => 'Success',
'message' => 'Success related message.'
);
}
}
return false;
}
You can use this method to define return value:
public function alert($id): ? array
{
$model = Model::find($id);
if ($model) {
if ($model->status != 1) {
return array(
'header' => 'Failed',
'message' => 'Failed related message'
);
} else {
return array(
'header' => 'Success',
'message' => 'Success related message.'
);
}
}
return null;
}
Which will end up in result of null or array.
I was read some answer in stackoverflow about this question, but I still not understand because the answer hasn't specified and make me confuse. I have some code below.
I use REST from https://github.com/chriskacerguis/codeigniter-restserver/
My Model API
public function upload(){
$config['upload_path']='./images/';
$config['allowed_types']='jpg|png|jpeg';
$config['max_size']='2048';
$config['remove_space']=TRUE;
$config['overwrite']=TRUE;
$this->load->library('upload',$config);
if ($this->upload->do_upload('id_image')) {
$return = array(
'result'=>'success',
'file'=> $this->upload->data(),
'error'=>'');
return $return;
} else {
$return = array(
'result'=>'failed',
'file'=>'',
'error'=> $this->upload->display_errors());
return $return;
}
}
public function createMember($upload){
$data_member = [
"id_card" => $this->input->post('id_card', true),
"name" => $this->input->post('name', true),
"email" => $this->input->post('email', true),
"id_image" => $upload['file']['file_name']
];
$this->db->insert('member', $data_member);
}
My Controller API
public function index_post(){
$upload = $this->Member_model_api->upload();
if ($this->Member_model_api->createMember($upload) > 0) {
$this->response([
'status' => true,
'message' => 'Member Data was Added'
], REST_Controller::HTTP_CREATED);
} else {
...
REST_Controller::HTTP_BAD_REQUEST);
}
}
Output from Postman
Message: Call to undefined method Member_model_api::upload()
Filename: C:\xampp\htdocs\org\application\controllers\api_controller\Org_member.php
I hope the other developers give me some reference like my code above, thank you very much.
I am trying to load all rows for my REST API through Postman.
I am using codeigniter-base-model MY_Model.php.
https://github.com/jamierumbelow/codeigniter-base-model
This is how my code currently looks like both in my controller/model:
Controller(api_news.php):
class Api_News extends REST_Controller {
function __construct()
{
parent::__construct();
}
function index_get()
{
$id = $this->uri->segment(3);
$this->load->model('News_model');
$news = $this->News_model->get_by(array('id' => $id));
if(isset($news['id'])) {
$this->response(array(
'message' => 'success',
'status' => 'true',
'data' => $news));
} else {
$this->response(array(
'message' => 'unsuccess',
'status' => 'false'));
}
}
}
Model(news_model.php):
class News_model extends MY_Model{
protected $_table = 'news';
protected $primary_key = 'id';
protected $return_type = 'array';
}
At the moment if I access:
localhost/my_api/api_news/id/1, 2, 3, etc...
I can access any record by its individual ID and it shows up which is great.
BUT I also want to be able to see all rows by doing this:
localhost/my_api/api_news/id/
and have all rows showing at once.
But I am not sure how to do this...and am getting an unsuccess/false if I try.
Can you please show me how? I am new to PHP in general and I appreciate any help.
Thank you so much!!
Make some changes in your Controller function as below -
function index_get(){
$id = $this->uri->segment(3);
$this->load->model('News_model');
// pass $id to model
$news = $this->News_model->get_by( $id );
if( !empty( $news ) ) {
$this->response(array(
'message' => 'success',
'status' => 'true',
'data' => $news));
} else {
$this->response(array(
'message' => 'unsuccess',
'status' => 'false'));
}
}
And in your model make id parameter optional and then check that if id is passed get data based on id otherwise return all data as below -
// $id variable is optional here
function get_by( $id = '' ) {
if ( $id == '' ) {
$news = $this->db->get( 'news' );
}
else {
$news = $this->db->get_where( 'news', array( 'id' => $id ) );
}
// return data to controller
return $news->result();
}
So if you enter id in API then data will be based on that id otherwise all data will be returned.
I am trying to insert an element into my 'category' table and use the inserted element's id to insert another element into my 'subcategory' table.
This is my code in my controller
public function insertCategory(){
$category = $this->input->post('category');
$subcategory = $this->input->post('subcategory');
$this->form_validation->set_rules('category', 'Category', 'required');
$this->form_validation->set_rules('subcategory', 'Subcategory', 'required');
if($this->form_validation->run() == FALSE){
$this->load->view('ADMIN_ADDCategory');
}
else{
$category_id = $this->admin_model->insertCategory($category);
$this->admin_model->insertSubcategory($category_id, $subcategory);
}
}
And this is my code in my model
function insertCategory($category){
$data = array(
'category' => $category,
'status' => 1
);
$this->db->insert('category', $data);
$this->db->select('id');
$this->db->from('category');
$this->db->where('category', $category);
$this->db->limit(1);
$query = $this->db->get();
return $query->result();
}
function insertSubcategory($category_id, $subcategory){
$data = array(
'category_id' => $category_id,
'subcategory' => $subcategory,
'status' => 1
);
$this->db->insert('subcategory', $data);
}
However I am getting this error
I already tried using $category_id = (array) $this->admin_model->insertCategory($category); but it still doesn't work
How do I overcome this error? Thank you for the help.
$this->admin_model->insertSubcategory($category_id, $subcategory);
$category_id is an array , so , you must do it like this:
$this->admin_model->insertSubcategory($category_id[0]->field, $subcategory);
You should try this
$this->admin_model->insertSubcategory($category_id[0]->id;, $subcategory);
try this code
Model
public function insert($table, $data)
{
if($this->db->insert($table,array $data))
{
return $this->db->insert_id();
}else
return false
}
controller
public function insertCategory(){
$this->form_validation->set_rules('category', 'Category', 'required');
$this->form_validation->set_rules('subcategory', 'Subcategory', 'required');
if($this->form_validation->run() == FALSE){
$this->load->view('ADMIN_ADDCategory');
}
else{
$category = $this->input->post('category');
$subcategory = $this->input->post('subcategory');
//data must be an array
$data = [
'category' => $category,
'status' => '1'
];
$category_id = $this->admin_model->insert('tablename',$data)
if($category_id != false)
{
$data = [
'category_id' => $category_id,
'subcategory' => $subcategory,
'status' => 1
];
if($this->admin_model->insert('table name', $data) != false)
{
echo 'success';
//or load your success page
}else{
echo 'failed';
//or load your success page
}
}else{
echo 'failed';
//or load your success page
}
}
}