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.
Related
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.
I have two separate APIs calls. One for click on edit page and another for update page:
The controller method when the user hits edit link:
public function EditList($page_id)
{
$listEdit= DB::table('page_master')->where('id',$page_id)->first();
return view('edit-list',compact('listEdit'));
}
and its route:
$router->get('/edit-List/{id}', 'AjaxController#EditList');
The above code successfully shows me the edit page where I will perform the update.
My next step is update record:
The controller method
public function updatePage($id)
{
$updatePage = $this->page->updatePage($id);
if(!$updatePage)
{
$resultArray = ['status' => 0, 'message' => 'Page not exist!'];
return Response::json( $resultArray, 400);
}
else{
$resultArray = ['status' => 1, 'message' => 'Page updated !'];
return Response::json($resultArray, 200);
}
}
and its routes:
Route::post('update/list/{id}',['uses' => 'ApiController#updatePage']);
Now when i click on update record it shows me the page does not exist even though the page is there in database but always showing the page does not exist page.
What should I change to make the routes work properly?
public function updatePage($id)
{
$updatePage = self::find($id);
if (is_null($updatePage)) {
return false;
}
$input = Input::all();
$updatePage->fill($input);
$updatePage->save();
return $updatePage;
}
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');
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);
I'd like some help please. I have a post page that has the full post and below the post a small form for adding comments. The uri of the post page is: site/posts/1, so it is in posts controller, and the form action is form_open(site_url('comments/add/'.$post->post_id)).
This is my add() function inside comments controller:
public function add($post_id){
// if nothing posted redirect
if (!$this->input->post()) {
redirect(site_url());
}
// TODO: save comment in database
$result = $this->comment_model->add($post_id);
if ($result !== false) {
redirect('posts/'.$post_id);
}
// TODO:load the view if required
}
and this is the add() function inside the comment model
public function add($post_id){
$post_data = array(
'post_id' => $post_id,
'username' => $this->input->post('username'),
'email' => $this->input->post('email'),
'comment' => $this->input->post('comment')
);
if ($this->validate($post_data)) {
$this->db->insert('comments', $post_data);
if ($this->db->affected_rows()) {
return $this->db->insert_id();
}
return false;
} else {
return false;
}
}
What I'm trying to do is if the $result = $this->comment_model->add($post_id); fails the validation to display the validation errors in my post view, else insert the comment and redirect to the same post page (site/posts/1).
The problem is that when I hit submit the form action goes in the comments/add/1, as expected, but doesn't do any these above.
Any ideas how can I fix this??
EDIT
I did a small change to the code without the 'confusing' validate() function. Maybe this is more helpful.
Comment controller:
public function add($post_id){
// if nothing posted redirect
if (!$this->input->post()) {
redirect(site_url());
}
// TODO: save comment in database
$this->form_validation->set_rules($this->comment_model->rules);
if ($this->form_validation->run() == true) {
echo "Ok! TODO save the comment.";
// $this->comment_model->add($post_id);
// redirect('posts/'.$post_id);
} else {
echo "Validation Failed! TODO: show validation errors!";
}
// TODO:load the view if required
}
Comment model:
public function add($post_id){
$post_data = array(
'post_id' => $post_id,
'username' => $this->input->post('username'),
'email' => $this->input->post('email'),
'comment' => $this->input->post('comment')
);
$this->db->insert('comments', $post_data);
if ($this->db->affected_rows()) {
return $this->db->insert_id();
}
return false;
}
You need away of passing validation_errors() back to your Posts controller. At the minute, when you perform the redirect in your add function (when the validation fails), you loose the validation errors thrown.
I would consider using flashdata (http://ellislab.com/codeigniter/user-guide/libraries/sessions.html) to pass a success/error message from your Comments controller back to your Posts controller. Something similar to the below:
Comments Controller:
public function add($post_id) {
// if nothing posted redirect
if (!$this->input->post()) {
redirect(site_url());
}
// TODO: save comment in database
$this->form_validation->set_rules($this->comment_model->rules);
if ($this->form_validation->run() == true) {
// Store the success message in flash data
$this->session->set_flashdata('message', 'Ok! TODO save the comment.');
// Redirect back to posts page
redirect('posts/'.$post_id, 'refresh');
} else {
// Store the error message in flash data
$this->session->set_flashdata('message', validation_errors());
// Redirect back to posts page
redirect('posts/'.$post_id, 'refresh');
}
}
Posts Controller:
public function index($post_id) {
$this->data['message'] = $this->session->flashdata('message');
$this->load->view('posts', $this->data);
}
Posts View:
echo $message;
Might not be perfect but hope it helps...