codeigniter status code 400 bad request in index_post() method - php

I keep on getting this error when performing post and put operations in my codeigniter restful api app.
here is the controller:
public function index_post(){
if(!$this->input->post('city'))
{
$this->response(null,400);
}
$id=$this->cities_model->save($this->input->post('city'));
if(!is_null($id))
{
$this->response(array('response'=> $id),200);
}
else
{
$this->response(array('error'=> 'sorry, data could not be saved...'),400);
}
}
public function index_put(){
if(!$this->input->post('city') || !$id)
{
$this->response(null,400);
}
$update=$this->cities_model->update($id,$this->input->post('city'));
if(!is_null($update))
{
$this->response(array('response' => 'content updated successfully'),200);
}
else
{
$this->response(array('error'=> 'sorry, technical error occurred, please try again later...'), 400);
}
}

There are few improvements and solution as per below.
public function index_post(){
// Use validation library, instead of checking just for value.
$this->load->library('form_validation');
$this->form_validation->set_rules('city','City','trim|required');
if($this->form_validation->run() == FALSE)
{
// send back list of validation errors.
$this->response($this->validation_errors(),REST_Controller::HTTP_BAD_REQUEST);
}
$id=$this->cities_model->save($this->post('city'));
if(!is_null($id))
{
$this->response(array('response'=> $id),REST_Controller::HTTP_OK);
}
else
{
$this->response(array('error'=> 'sorry, data could not be saved...'),REST_Controller::HTTP_BAD_REQUEST);
}
}
public function index_put(){
// for put you need to pass id as parameter
// Use validation library, instead of checking just for value.
$this->load->library('form_validation');
$this->form_validation->set_rules('id','ID','trim|required|integer');
$this->form_validation->set_rules('city','City','trim|required');
if($this->form_validation->run() == FALSE)
{
// send back list of validation errors.
$this->response($this->validation_errors(),REST_Controller::HTTP_BAD_REQUEST);
}
$update=$this->cities_model->update($this->post('id'),$this->post('city'));
if(!is_null($update))
{
$this->response(array('response' => 'content updated successfully'),REST_Controller::HTTP_OK);
}
else
{
$this->response(array('error'=> 'sorry, technical error occurred, please try again later...'), REST_Controller::HTTP_BAD_REQUEST);
}
}
Now you need to pass city parameter from postman in POST body. it invoke index_post and you pass city and id parameter in PUT body,it invoke index_put.

class Cities_model extends CI_Model
{
public function __construct()
{
parent::__construct();
}
public function save($city)
{
$this->db->set($this->setCity($city))->insert('cities');
if($this->db->affected_rows()>0)
{
return $this->db->insert_id;
}
return null;
}
public function update($id,$city)
{
$this->db->set($this->setCity($city))->where('id',$id)->update('cities');
if($this->db->affected_rows()===1)
{
return true;
}
return false;
}
private function setCity($city)
{
return array('id'=>$city['id'],
'name'=>$city['name']
);
}
}

Related

Laravel withValidator() not working as expected

I have this formrequest that contains rules and a withValidator as a second layer of validation.
Note: I am aware that having it unique on the rules would supress the need for this example, but I'll need to do further validations here.
public function rules(Request $request) {
return [
"name" => "required|max:191",
"begin_date" => "required|after_or_equal:today|date_format:d-m-Y",
"end_date" => "required|after:begin_date|date_format:d-m-Y",
];
}
public function withValidator($factory) {
$result = User::where('name', $this->name)->get();
if (!$result->isEmpty()) {
$factory->errors()->add('User', 'Something wrong with this guy');
}
return $factory;
}
I am positive that it enters the if as I've placed a dd previously it to check if it's going inside. However, it proceeds to this method on the Controller and I don't want it to.
public function justATest(UserRequest $request) {
dd("HI");
}
I'm an idiot and didn't read the full doc.
It needs to specify with an after function,like this:
public function withValidator($factory) {
$result = User::where('name', $this->name)->get();
$factory->after(function ($factory) use ($result) {
if (!$result->isEmpty()) {
$factory->errors()->add('User', 'Something wrong with this guy');
}
});
return $factory;
}
I was facing this problem too.
I changed my withValidator to this:
public function withValidator($validator)
{
if (!$validator->fails()) {
$validator->after(function ($validator) {
if (Cache::has($this->mobile)) {
if (Cache::get($this->mobile) != $this->code) {
$validator->errors()->add('code', 'code is incorrect!');
} else {
$this->user = User::where('mobile', $this->mobile)->first();
}
} else {
$validator->errors()->add('code', 'code not found!');
}
});
}

Custom error message using CodeIgniter and Pregmatch Form Validation

it is not working, what should i do to make it work ?
if (preg_match('(?=.*[a-z])(?=.*[A-Z]).*', $str))
{
return TRUE;
}
else
{
$this->form_validation->set_message('user_password1', 'Please provide a stronger password');
return FALSE;
}
use your own validation methods some thing like this
<?php
class Form extends CI_Controller {
public function index()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('password', 'Password', 'required|callback_password_check');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('myform');
}
else
{
$this->load->view('formsuccess');
}
}
public function password_check($str)
{
if (preg_match('(?=.*[a-z])(?=.*[A-Z]).*', $str))
{
return TRUE;
}
else
{
$this->form_validation->set_message('password_check' , 'Please provide a stronger password');
return FALSE;
}
}
}

codeigniter restful api illegal string offset in several fields

I keep on getting this error in my codeigniter micro app restful api. When I post an item only the first letter is get saved with status code 400 being displayed.
here is my model file:
class Cities_model extends CI_Model {
public function __construct()
{
parent::__construct();
}
public function save($city)
{
$this->db->set($this->setCity($city, null))->insert('cities');
if ($this->db->affected_rows() > 0) {
return $this->db->insert_id;
}
return null;
}
public function update($id, $city)
{
$this->db->set($this->setCity($city))->where('id')->update('cities');
if ($this->db->affected_rows() === 1) {
return true;
}
return false;
}
private function setCity($city)
{
return array(
'id' => $city['id'],
'name' => $city['name']
);
}
}
As you can see setCity function treat $city variable as array. So you need to pass array to setCity function.
class Cities_model extends CI_Model {
public function __construct()
{
parent::__construct();
}
public function save($city)
{
$this->db->insert('cities',$this->setCity(array('name'=>$cit‌​y,'id'=> null)));
if ($this->db->affected_rows() > 0) {
return $this->db->insert_id();
}
return null;
}
public function update($id, $city)
{
$this->db->where('id',$id)->update('cities',$this->setCity(array('name'=>$cit‌​y,'id'=> $id)));
if ($this->db->affected_rows() === 1) {
return true;
}
return false;
}
private function setCity($city)
{
return array(
'id' => $city['id'],
'name' => $city['name']
);
}
}
another thing is, Codeignitor having method insert_id() to know last insert id.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
require APPPATH . '/libraries/REST_Controller.php';
class Cities extends REST_Controller{
public function __construct() {
parent::__construct();
$this->load->model('cities_model');
}
public function index_get(){
$cities=$this->cities_model->get();
if(!is_null($cities))
{
$this->response(array('response'=>$cities),200);
}
else
{
$this->response(array('error'=>'cities cannot be found...'),404);
}
}
public function find_get($id){
if(!$id)
{
$this->respose(null,400);
}
$cit=$this->cities_model->get($id);
if(!is_null($cit))
{
$this->response(array('response'=> $cit),200);
}
else{
$this->response(array('error'=> 'data could not be found...'),404);
}
}
public function index_post(){
// Use validation library, instead of checking just for value.
$this->load->library('form_validation');
$this->form_validation->set_rules('city','City','trim|required');
if($this->form_validation->run() == FALSE)
{
// send back list of validation errors.
$this->response($this->validation_errors(),REST_Controller::HTTP_BAD_REQUEST);
}
$id=$this->cities_model->save($this->post('city'));
if(!is_null($id))
{
$this->response(array('response'=> $id),REST_Controller::HTTP_OK);
}
else
{
$this->response(array('error'=> 'sorry, data could not be saved...'),REST_Controller::HTTP_BAD_REQUEST);
}
}
public function index_put(){
// for put you need to pass id as parameter
// Use validation library, instead of checking just for value.
$this->load->library('form_validation');
$this->form_validation->set_rules('id','ID','trim|required|integer');
$this->form_validation->set_rules('city','City','trim|required');
if($this->form_validation->run() == FALSE)
{
// send back list of validation errors.
$this->response($this->validation_errors(),REST_Controller::HTTP_BAD_REQUEST);
}
$update=$this->cities_model->update($this->post('id'),$this->post('city'));
if(!is_null($update))
{
$this->response(array('response' => 'content updated successfully'),REST_Controller::HTTP_OK);
}
else
{
$this->response(array('error'=> 'sorry, technical error occurred, please try again later...'), REST_Controller::HTTP_BAD_REQUEST);
}
}
public function index_delete($id){
if(!$id)
{
$this->response(null,400);
}
$del=$this->cities_model->delete($id);
if(!is_null($del))
{
$this->response(array('response'=> 'item successfully deleted'),200);
}
else{
$this->response(array('error'=> 'delete operations could not be done...'),400);
}
}
}
here is the model file:
<?php
class Cities_model extends CI_Model
{
public function __construct()
{
parent::__construct();
}
public function get($id=null)
{
if(!is_null($id))
{
$query=$this->db->select('*')->from('cities')->where('id',$id)->get();
if($query->num_rows()===1)
{
return $query->row_array();
}
return null;
}
$sql=$this->db->select('*')->from('cities')->get();
if($sql->num_rows()>0)
{
return $sql->result_array();
}
return null;
}
public function save($city)
{
$this->db->insert('cities', array('name'=>$city));
if($this->db->affected_rows()>0)
{
return $this->db->insert_id();
}
return null;
}
public function update($id, $city)
{
$this->db->where('id',$id)->update('cities',$this->setCity(array('name'=>$cit‌​y,'id'=> $id)));
if ($this->db->affected_rows() === 1) {
return true;
}
return false;
}
private function setCity($city)
{
return array('id'=>$city['id'],
'name'=>$city['name']
);
}
public function delete($id)
{
$this->db->where('id',$id)->delete('cities');
if($this->db->affected_rows()===1)
{
return true;
}
return false;
}
}

how to use callback in codeigniter

I'm using codeigniter and I want to create validation for name field if the name exists in my table. ut I'm getting blank screen, can everyone help me?
this is my controller:
public function insertCabang(){
$this->load->library('form_validation');
$this->form_validation->set_rules('name', 'nama_cabang', 'trim|required|callback_isNameExist');
}
public function isNameExist($name) {
$this->load->library('form_validation');
$is_exist = $this->cabang_model->isNameExist($name);
if ($is_exist) {
$this->form_validation->set_message('isNameExist', 'Name is already exist.');
return false;
} else {
return true;
}
}
and this is my model
public function isNameExist($name) {
$this->db->select('nama_cabang');
$this->db->where('nama_cabang', $name);
$query = $this->db->get('master_cabang');
if ($query->num_rows() > 0) {
return true;
} else {
return false;
}
}
After submit I get the blank screen.
Thanks,
Martin
You can simply use is_unique to perform this action instead of using callback.
Your syntax will be
$this->form_validation->set_rules('name', 'nama_cabang', 'trim|required|is_unique[master_cabang.nama_cabang]');
The problem is on your insertCabang() controller function. You run the
validation, but what should it do after? You must echo the result, or load some view.
public function insertCabang(){
$this->load->library('form_validation');
$this->form_validation->set_rules('name', 'nama_cabang', 'trim|required|callback_isNameExist');
if($this->form_validation->run()){
echo 'validated ok';
}else{echo validation_errors();}
}

Callback Function Error ( Unable to access an error message corresponding to your field name )

I am new to Codeigniter. I have error when i try to check the email is existed or not. I saw lot of post on Stackoverflow and other website. I can't get any result.
When i try with below coding i got below errors
Unable to access an error message corresponding to your field name
Email.(email_check)
Please check my code.
Controller
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Main extends CI_Controller {
public function index()
{
$this->login();
}
public function login()
{
$this->load->view('login');
}
public function login_validation()
{
$this->load->library('form_validation');
$this->form_validation->set_rules("email","Email","required|trim|callback_email_check");
$this->form_validation->set_rules("password","Password","required|md5|trim|callback_password_check");
if($this->form_validation->run())
{
redirect('main/members');
}
else
{
$this->load->view('login');
}
}
public function members()
{
$this->load->model('model_users');
if($this->model_users->can_log_in())
{
return true;
}
else
{
$this->form_validation->set_message('email_check', 'Incorrect Username/Password');
return false;
}
}
}
MODEL
<?php
class Model_users extends CI_Model
{
public function can_log_in()
{
$this->db->where->('email',$this->input->post('email'));
$this->db->where->('password',md5($this->input->post('password')));
$query = $this->db->get('users');
if($query->num_rows == 1)
{
return true;
}
else
{
return false;
}
}
}
?>
I believe you are missing your callback function email_check, and there the set_message should correspond to the function and not the field itself.
You will have to add the 2 callback functions that you are using :
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Main extends CI_Controller {
public function index()
{
$this->login();
}
public function login()
{
$this->load->view('login');
}
public function login_validation()
{
$this->load->library('form_validation');
$this->form_validation->set_rules("email","Email","required|trim|callback_email_check");
$this->form_validation->set_rules("password","Password","required|md5|trim|callback_password_check");
if($this->form_validation->run())
{
redirect('main/members');
}
else
{
$this->load->view('login');
}
}
public function email_check(){
//perform your validation here
if({your_validation_result}){
return true;
}else{
$this->form_validation->set_message('email_check', 'Incorrect Username/Password');
return false;
}
}
public function password_check(){
//perform your validation here
if({your_validation_result}){
return true;
}else{
$this->form_validation->set_message('password_check', 'Incorrect Username/Password');
return false;
}
}
public function members()
{
$this->load->model('model_users');
if($this->model_users->can_log_in())
{
return true;
}
else
{
$this->form_validation->set_message('email_check', 'Incorrect Username/Password');
return false;
}
}
}

Categories