how to delete the database from restfull api using codeigniter - php

please help me to solve this issue
Model Code
this is the model section and i want to delete pariticular row from the database but it does't works
public function update($id, $data){
$this->db->where('id', $id);
if($this->db->update('tbl_books', $data)){
return true;
}else{
return false;
}
}
Controller code
whenever i try to delete the data it shows error,
function deleteBook_delete()
{
$id = $this->delete('id');
if(!$id){
$this->response("Parameter missing", 404);
}
if($this->book_model->delete($id))
{
$this->response("Success", 200);
}
else
{
$this->response("Failed", 400);
}
}

From the CodeIgniter docs: https://www.codeigniter.com/userguide3/database/query_builder.html#deleting-data
$this->db->delete('tbl_books', array('id' => $id));

Write database related code into the model not in controller and use code below to delete row from the table
$this->db->delete('table name', array('id' => $id));

$this->db->delete('tbl_user', array('id' => $id));
or
$this->db->where('id', $id);
$this->db->delete('tbl_user');

Related

Laravel restore back deleted record

I'm trying to implement the queue that system will be restored back a deleted record. Now my code is working without error but the record will not restore back after deleted.
public function delete_invoice($job, $data)
{
Debugbar::info("invoiceSale");
try {
return DB::transaction(function ()use ($job,$data) {
});
} catch (TransactionException $e) {
# reestore function
extract($data);
$data = $Class::withTrashed()->find($id);
$data->restore();
Debugbar::info($data->toArray());
return Response::json(['errors' => array_flatten($e->getErrors())], 400);
}
}
This is the function from controller
public function destroy($id, $message = '')
{
Debugbar::info("ok");
Queue::push('IQueue#delete_invoice', [
'id' => $id,
'Class' => $this->Class,
]);
return parent::destroy($id, trans("$this->class.invoice")); <--delete invoice
}
you can use the following code hope it will help you.
public function destroy(Trip $trip)
{
$trip->delete();
flash()->warning('Trip '.$trip->id.' successfully deleted! <a href=trips/'.$trip->id.'/restore>UNDO</a>');
return redirect('trips');
}
public function restore(Request $request)
{
$trip = Trip::withTrashed()->where('id', $request['id'])->restore();
return redirect ('trips');
}
I'm assuming your code deletes the record somewhere else and the code you presented here is supposed to restore that record, based on the model class and record id passed via the $data array as ['Class' => ..., 'id' => ...].
Then what is your transaction meant to do? Is there any code you did not paste in? Otherwise catch is never called as there is no exception thrown and hence you code is not executed.
So just remove the try and catch.

Data not insert into codeigniter

I will try to insert & also update data using session in Codeigniter, but data not inserted into the database even its print save successfully.
Here is my controller:
public function save($user_id)
{
$this->load->model('Users');
$code=$this->input->post('code');
$name=$this->input->post('name');
$address=$this->input->post('address');
$user_data= array(
'code' =>$code,
'name'=>$name,
'address'=>$address,
'active'=>1
);
if($this->Users->save($user_data,$user_id))
{
$this->session->set_flashdata('msg',"save sucesss");
}else {
$this->session->set_flashdata('msg',"not save");
}
redirect('home');
}
& this is my model:
public function save($data,$id)
{
if (id=='') {
// code...
$this->db->insert('user',$data);
return true;
}else
{
$this->db->where('id',$id)
->update('user',$data);
return true;
}
return false;
}
Data insert if I removed if in model!
You have the model always returning true no matter the outcome of the database operation. You should use the return value from insert() or update() so the "message" reports what actually happens.
Note that the argument to save has a default value. Now you can call the save URL without an argument and it will automatically do an insert.
public function save($user_id = NULL)
{
$this->load->model('users');
$user_data = array(
'code' => $this->input->post('code'),
'name' => $this->input->post('name'),
'address' => $this->input->post('address'),
'active' => 1
);
if($this->Users->save($user_data, $user_id))
{
$msg = "save sucesss";
}
else
{
$msg = "not save";
}
$this->session->set_flashdata('msg', $msg);
redirect('home');
}
public function save($data, $id)
{
if(empty($id))
{
// code...
// insert returns TRUE on success, FALSE on failure
return $this->db->insert('user', $data);
}
// update() accepts a third argument, a "where" array
// and returns TRUE on success, FALSE on failure
return $this->db->update('user', $data, array('id' => $id));
}
Now have an accurate report on the database operations.
the first check is data is coming in save controller or not if it's not getting the data then fix it. If coming then pass it in a model in the correct format and it will definitely be inserted in the database.
use following printing data
echo $data;
var_dump($data);
print($data);
print_r($data);
First thing is to rename your model calling eg:
$this->load->model('users');
and use this to call your method:
$this->users->save($user_data,$user_id)
your model should look like this then:
public function save($data, $id) {
if ($id) {
$this->db->where('id', $id)
->update('user', $data);
return true;
}
$this->db->insert('user', $data);
return true;
}
if you want to use your flashdata on the next request, use this:
$this->session->keep_flashdata('item');
$this->session->keep_flashdata(array('item1', 'item2', 'item3'));
because flashdata is only for the next request:
CodeIgniter supports “flashdata”, or session data that will only be available for the next request, and is then automatically cleared.

how can I get price cart from database in Code Igniter

it's my controller
function set_hargabesar($id){
$this->load->library('cart');
$condition['id'] = 'id';
$get = $this->myigniter_model->getharga('harga_satuan','id');
$data = array(
'rowid' => $id,
'qty' => 5,
'price' => $get,
);
$this->cart->update_all($data);
}
it's my model
public function getharga($harga, $id){
$this->db->select($harga);
$this->db->from('barang');
$this->db->where('id',$id);
$query=$this->db->get();
}
How can I get a 'harga_satuan' (price cart) from database
please help me.
I can get the data(harga_satuan) from database with this code.
You've only executed your query, you need to retrieve data.
Model:
public function getharga($harga, $id){
$this->db->select($harga);
$this->db->from('barang');
$this->db->where('id',$id);
$query=$this->db->get();
$row = $query->row_array();
return $row;
}
In your controller just change this:
'price' => $get['harga_satuan'],
And, of course, you need to pass id to your model:
$get = $this->myigniter_model->getharga('harga_satuan', $id);
(but I hope you are doing it)

how to update table using api in codeigniter

I'm stuck at updating table row using api in codeigniter,
i already have read tutorial from code tutsplus
but there's no spesific to do it,
so i tried by myself and got stuck :-(
url request:
http://localhost/work/bnilife/v1/signup/user/post?nopol=a1b2c3d4e5&username=agus&password=kucingtikus&captcha=c12ds
Here's the json respon:
{
"error": "error :-( "
}
My Controller look like this below:
public function user_post()
{
date_default_timezone_set('Asia/Jakarta');
$datestring ="%Y-%m-%d %H:%i:%s";
$time =time();
$datetime =mdate($datestring, $time);
$data = array (
'nopol' => $this->input->get_post('nopol'),
'username' => $this->input->get_post('username'),
'password' => sha1($this->input->get_post('password')),
'created_at' => $datetime,
'updated_at' => $datetime
);
$result = $this->signup_m->signup_insert($data);
if($result) {
$this->response($data, 200);
} else {
$this->response(array('error' => 'error :-( '),400);
}
}
My model:
public function signup_insert($data) {
// Query to check whether username already exist or not
$condition = "nopol=" . "'" . $data['nopol'] . "'" ;
$this->db->where($condition);
$this->db->update('user', $data); }
Is there any something wrong or misstype,
thank you guys
i'm new at this stuff.
You can check codeigniter documentation how are working Database methods http://www.codeigniter.com/userguide3/database
public function signup_insert($data) {
$this->db->where('nopol',$data['nopol']);
return $this->db->update('user', $data);
}
In your case you need and return else you can't use the method as $result as it will be equal to NULL..
Check and CI Form Validation library as you don't validate your input data (even escaped) it may generate problems.
And importantly, you should write proper method names: signup_insert should INSERT not UPDATE.
'nopol' => $this->input->get_post('nopol') in this change to 'nopol' => $this->input->get_post('no_polis'),
also $this->db->where($condition) $condition is not defined.
Like #svetlio said,
i add some solution if nopol is typo(misstype) or null.
it will return false,
so i add some code to do it.
like this below:
if ($this->db->affected_rows() === 1) {
return true;
} else {
return false;
}
}
so it wont be like:
return $this->db->update('user', $data);

Yii framework. Can't save model

I have problem with Yii. I have following code in controller:
...
$user = User::model()->find("user_id = :id AND type='1'", array('id'=>$user->id));
$user->time=new CDbExpression('NOW()');
$user->status=1;
$user->save();
...
And Im getting this error:
Call to undefined method stdClass::save()
What's wrong?
oo i see you need to test if you have a user
just do :
if($user)
is your model extand a CactiveRecord ?
you should display the errors to know what's wrong
if(!$user->save()){
var_dump($user->getErrors());
}
this will be helpfull
Your error is to classic to knwo exactly what went wrong! here's a problem that could be the reason of your error:
When you find your user, if it doesn't find it the method will return false then the rest of the operations will fail. You should perform something like:
$user = User::model()->find("user_id = :id AND type='1'", array('id'=>$user->id));
if($user !== null) {
$user->time=new CDbExpression('NOW()');
$user->status=1;
$user->save();
}
if ($model->load(Yii::$app->request->post())) {
$model->startDate = $modifiedStartDate;
$model->timeFrom = $modifiedFromTime;
$model->timeTo = $modifiedToTime;
//echo '<pre>';
//print_r($model);exit;
$model->save();
//return $this->redirect(['view', 'id' => $model->id]);
return $this->redirect(['timelog/index']);
} else {
return $this->render('create',
[
'model' => $model,
]);
}
//why the error occurs while using the $method->save(); function.

Categories