Can't insert data via rest api - php

I try using rest api in codeigniter to insert data.
I try this
public function sensor_post(){
$data = array(
'sensor_id' => $this->input->post('sensor_id'),
'value' => $this->input->post('value'));
$insert = $this->db->insert('measurement', $data);
if ($insert) {
$this->response($data, 200);
} else {
$this->response(array('status' => 'fail', 502));
}
}
And call
http://localhost/rest_iot/index.php/iot/sensor?sensor_id=1&value=37
I try this in post man and I get error like this. I think I've fill the value, why this is happend?
<h1>A Database Error Occurred</h1>
<p>Error Number: 1048</p>
<p>Column 'sensor_id' cannot be null</p>
<p>INSERT INTO `measurement` (`sensor_id`, `value`) VALUES (NULL, NULL)</p>
<p>Filename: C:/xampp/htdocs/rest_iot/system/database/DB_driver.php</p>
<p>Line Number: 691</p>

If you are sending the data within the URL, you are sending it via GET. However your code is trying to receive data sent via POST.
I presume in codeigniter you can simply write the code as follows to receive it as GET:
'sensor_id' => $this->input->get('sensor_id'),
'value' => $this->input->get('value')

Either you are sending data via GET or POST ? Assuming that $this->post('sensor_id') you are looking for POST but sending via GET sensor_id=1&value=37.
Send data via POST method or... retrieve via GET

You are missing input in your post fields.
public function sensor_post()
{
$data = array(
'sensor_id' => $this->input->post('sensor_id'),
'value' => $this->input->post('value')
);
$insert = $this->db->insert('measurement', $data);
if ($insert) {
$this->response($data, 200);
} else {
$this->response(array('status' => 'fail', 502));
}
}
This will work for you.

Related

Insert multiple json data into mysql database from postman using codeigniter api

I am tring to insert multiple data in db using postman but only single data is insetred successfully ,when inserting multiple data getting 500 error.Please help me on how can i insert multiple data in db.Any help would be highly appreciated.Thank you.
PostMan raw data:
[{
"total_sales":"14",
"total_product":"21",
"total_profit":"5099",
"total_distributor":14,
"total_ratail":40 },
{
"total_sales":14,
"total_product":21,
"total_profit":50,
"total_distributors":14,
"total_ratail":40 }
]
Below is my code:
public function create()
{
$model = new AdminModel();
print_r("total_sales");
$data = array(
'total_sales'=>$this->request->getVar('total_sales'),
'total_product'=>$this->request->getVar('total_product'),
'total_profit'=>$this->request->getVar('total_profit'),
'total_distributors'=>$this->request->getVar('total_distributors'),
'total_ratail'=>$this->request->getVar('total_ratail'),
);
$query = $model->where('id', $data['total_sales'])->find();
if(count($query)>0){
$model->update->where('id', $data['total_sales'])->find();
}
else{
$model->insert($data);
}
//$model->insert($data);
$response = [
'status' => 200,
'error' => null,
'messages' => [
'success' => 'Data Saved'
]
];
return $this->respondCreated($response);
}
You are adding an array of objects but the code is expecting only one object. That's why you are getting the error.
You have to modify your php code to accept an array and loop through them.

Codeigniter Rest API : Put request doesn't get passed id

I developed a REST API using REST Library for Phil Sturgeon,
GET and POST requests working fine ,
Now when I try to access the passed params with PUT request, I get null.
class ApiItems extends REST_Controller
{
function __construct() {
//
}
public function items_get(){ // //}
public function items_post(){ // //}
public function items_put()
{
if(!$this->put('id')) //My issue : I can't get the id here
{
$this->response(array('error' => 'Item id is required'), 400);
}
$data = array(
'id' => $this->put('id'),
'code'=> $this->put('code'),
'name' => $this->put('name'),
'quantity' => $this->put('quantity')
);
$this->item_model->update_item($this->put('id'), $data);
$message = array('success' => $id.' Updated!');
$this->response($message, 200);
}
}
I tested it using POSTMAN and I get this :
POSTMAN PUT Call screenshot
I dont understand why $this->get(id) or $this->post(id) are working fine,and not the case for $this->put(id) ?
It's working ,I ve done a stupid mistake when filling the parameters with POSTMAN, I checked form-data instead of x-www-form-url-encoded

Update Codeigniter form - refresh

I'm having a form which retrieves the values from the database and updates it by submitting the form.
First time when I'm accessing the page, it works, it retrieves the values, but if I'm updating the values through the form it retrieves the new values only after refreshing manually the page.
How can I refresh it automatically?
Also, if I'm accessing the page, not doing an update, and refreshing it, everything it's deleted, including the values form the database.
This is the controller:
public function edit_profile()
{
$id=$_SESSION['user_id'];
$this->load->model('retrieve');
$upd = array
(
'Name' => $this->input->post('name'),
'surname' => $this->input->post('surname'),
'Id_loc' => $this->input->post('id_loc')
);
$data['info']=$this->retrive->select_Info($id);
$this->retrieve->update_info($id,$upd);
$this->load->view('edit_profile', $data);
}
And this is the model:
function update_info($id,$data){
$this->db->where('id', $id);
$this->db->update('users', $data);
}
your code will look like this: with two functions
public function edit_profile()
{
$id=$_SESSION['user_id'];
$data['info']=$this->retrive->select_Info($id);
$this->load->view('edit_profile', $data);
}
public function saveUpdate()
{
$id=$_SESSION['user_id'];
$this->load->model('retrieve');
$upd = array
(
'Name' => $this->input->post('name'),
'surname' => $this->input->post('surname'),
'Id_loc' => $this->input->post('id_loc')
);
$update = $this->retrieve->update_info($id,$upd);
if($update)
{
redirect('YURCTRLER/edit_profile');
}
}
add the following code to your controller after an update is done:
redirect($this->uri->uri_string());
or
redirect('YOURCONTROLLER/edit_profile', 'refresh');
For the case of deleting, the code you have provided I think is not enough to deduce the problem :-(

ROUTE PARAMETER DISAPPEAR AFTER SAVE DATA

Hi everyone I need help with this problem. I am programming an application using php with laravel framework. My current laravel framework version is 4.2.11
I have this route to handle POST & GET actions
Route::any("/myaccount2/ausersave/{code?}", array("as" => "ausersave",
"uses" => "PrivateController#ausersave"))->before('auth_admin');
When I use Get action with mydomain/myaccount2/ausersave/90
I get list all data ok. But when I post all data to save the url change to mydomain/myaccount2/ausersave (parameter 90 is missing)
I guest this change is before the data is saved because the {code?} or 90 parameter is missing.
So I was looking for a function that allowed my application to post data and keeps the old url (mydomain/myaccount2/ausersave/90)
I find this function Redirect::back() but some post don't recommend to use it
I will apreciate your help. Thanks
My controller function is:
public function ausersave($code = 'null') {
$messg = null;
if(Input::get("userid") != null && Input::get("personid") != null) {
return View::make('PrivateController.ausersave', array('message' =>'Ok',
'user' => null, 'children' => null));
}
else if(isset($code)) {
return View::make('PrivateController.ausersave',
$this->ausersaveGet($code) );
}
return View::make('PrivateController.ausersave',
array('message' => '', 'user' => null,
'children' => null));
}
$this->ausersaveGet($code) -> this function bring me data form database and return me an array with thosse values array('message' => '', 'user' => $user, 'children' => $children); where user has info about user and children is an array of data. All this data return ok.
I would try taking the the ? out of the route parameter. i.e. change this:
Route::any("/myaccount2/ausersave/{code?}", array(......
to this:
Route::any("/myaccount2/ausersave/{code}", array(......

How to insert an object into MongoDB document using Laravel 4

I am a newbie in Laravel MongoDB I would like to mention a problem here, outline of my Mongo document should be like
{
_id:****,
subscriptions: [{list_id: "14Q3"},
{list_id: "153"}],
offers: [ { targetURL: "www.qwerty.com", title: "25% discount" },
{ targetURL: "www.abcd.com", title: "55% discount" } ],
}
I have used the following code to insert a list id (was successful).
DB::connection('mongodb')->collection('subscribers')->insert(array(
'_id' => $subscriber->device_id,
'subscriptions' => array('list_id' => $subscriber->list1_id),
));
But when I try to push another list_id as next object it is showing error. I used the following code for pushing
DB::connection('mongodb')->collection('subscribers')
->push('subscriptions', array('list_id' => $subscriber->list1_id));
I don't know whether my code is right or wrong. I need to store the data as the outline given above. This is My actual problem. Please correct me....
My controller is is given below, I create new collection for each subscriber. Problem is second 'if' statement
public function store() {
$newsubscriber = Input::json();
//DB::connection('mongodb')->collection($newsubscriber->get('device_id'))->delete();
$result = Subscriber::where('list1_id',$newsubscriber->get('list_id'))->where('device_id',$newsubscriber->get('device_id'))->get();
if (!$result->isEmpty()) {
return "You are already a subscriber of this List";
}
else{
$result1 = Subscriber::where('device_id',$newsubscriber->get('device_id'))->get();
$subscriber = new Subscriber();
$subscriber->list1_id = $newsubscriber->get('list_id');
$subscriber->device_id = $newsubscriber->get('device_id');
$subscriber->subtype = 1;
$subscriber->save();
if (!$result1->isEmpty()) {
DB::connection('mongodb')->collection($subscriber->device_id)->push('subscriptions', array('list_id' => $subscriber->list1_id));
return "Subscribed successfully 1";
}
else{
DB::connection('mongodb')->collection($subscriber->device_id)->insert(array('_id' => $subscriber->device_id,'subscriptions' => array('list_id' => $subscriber->list1_id),
));
return "Subscribed successfully 2";
}
}
}
First i have used following API
curl -H "Content-Type: application/json" -d '{"list_id":"2","device_id":"987654321"}' http://localhost/lemmeknw/public/index.php/api/v1/subscribe
This returned "Subscribed successfully 2"
but when I used API for second time
curl -H "Content-Type: application/json" -d '{"list_id":"1","device_id":"987654321"}' http://localhost/lemmeknw/public/index.php/api/v1/subscribe
There was error "Something went wrong"
I don't know much about Laravel, but what I'm seeing here:
DB::connection('mongodb')->collection('subscribers')->insert(array(
'_id' => $subscriber->device_id,
'subscriptions' => array('list_id' => $subscriber->list1_id),
));
Looks like you are creating subscriptions as an object {list_id: <subscriber-list1_id>} instead of an array of one object [{list_id: <subscriber-list1_id>}]. So when you try to use the push operation
DB::connection('mongodb')->collection('subscribers')
->push('subscriptions', array('list_id' => $subscriber->list1_id));
that is an attempt to push to an object, not an array. My guess is that you will need to modify your insert to be
DB::connection('mongodb')->collection('subscribers')->insert(array(
'_id' => $subscriber->device_id,
'subscriptions' => array(array('list_id' => $subscriber->list1_id)),
));

Categories