i couldn't insert data to database in codeigniter - php

i couldn't insert data to database and no error display. i try var_dump($this->mberita->get_berita()); but array(0){}. I am a newbie in Codeigniter and couldn't really figure out how to solve this.
modal
function get_berita()
{
$this->db->order_by('id_berita','asc');
$data = $this->db->get('berita_ukm');
return $data->result();
}
//untuk menambah berita
function insert_berita($data)
{
$this->db->insert('berita_ukm', $data);
}
controller
function index()
{
$this->data['berita'] = $this->mberita->get_berita();
$this->data['title'] ='UKM Taekwondo | berita';
$this->data['orang'] = $this->mlogin->dataPengguna($this->session->userdata('username'));
$this->data['contents'] = $this->load->view('admin/berita/view_berita', $this->data, true);
$this->load->view('template/wrapper/admin/wrapper_ukm',$this->data);
}
function tambah_berita()
{
$this->form_validation->set_rules('id_berita', 'Id Berita', 'required|numeric');
$this->form_validation->set_rules('tanggal', 'Tanggal', 'required');
$this->form_validation->set_rules('judul_berita', 'Judul Berita', 'required');
$this->form_validation->set_rules('content', 'Content', 'required');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('admin/berita/tambah_berita');
}else{
$this->load->model('mberita');
$data = array(
'id_berita' => $this->input->post('id_berita'),
'tanggal' => $this->input->post('tanggal'),
'judul_berita' => $this->input->post('judul_berita'),
'content' => $this->input->post('content')
);
$this->mberita->insert_berita($data);
}
$this->data['orang'] = $this->mlogin->dataPengguna($this->session->userdata('username'));
$this->data['contents'] = $this->load->view('admin/berita/tambah_berita', '', true);
$this->load->view('template/wrapper/admin/wrapper_ukm',$this->data);
}
Please help me what to do. Thank you.

Seems you may be missing the data you want to insert:
$this->mberita->insert_berita($data);

Your data is in the array data.But you don't pass it to the model.
So rewrite the code in controller as
$this->mberita->insert_berita($data);

Related

Codeigniter blog application bug: form is loaded without validation errors

I am working on a blog application in Codeigniter 3.1.8 and Bootstrap 4. I have an "Edit post" form with validation.
If validation fails (because the Title field has been emptied, for example), the form should reload with validation errors.
My update() (lives in the Posts controller) method is wrong: it uses a redirect, so the form is reloaded without validation errors, to its initial state.
public function edit($id) {
// Only logged in users can edit posts
if (!$this->session->userdata('is_logged_in')) {
redirect('login');
}
$data = $this->Static_model->get_static_data();
$data['pages'] = $this->Pages_model->get_pages();
$data['categories'] = $this->Categories_model->get_categories();
$data['posts'] = $this->Posts_model->sidebar_posts($limit=5, $offset=0);
$data['post'] = $this->Posts_model->get_post($id);
if ($this->session->userdata('user_id') == $data['post']->author_id) {
$data['tagline'] = 'Edit the post "' . $data['post']->title . '"';
$this->load->view('partials/header', $data);
$this->load->view('edit-post');
$this->load->view('partials/footer');
} else {
/* If the current user is not the author
of the post do not alow edit */
redirect('/' . $id);
}
}
public function update() {
// Form data validation rules
$this->form_validation->set_rules('title', 'Title', 'required', array('required' => 'The %s field can not be empty'));
$this->form_validation->set_rules('desc', 'Short description', 'required', array('required' => 'The %s field can not be empty'));
$this->form_validation->set_rules('body', 'Body', 'required', array('required' => 'The %s field can not be empty'));
$this->form_validation->set_error_delimiters('<p class="error-message">', '</p>');
$id = $this->input->post('id');
// Update slug (from title)
if (!empty($this->input->post('title'))) {
$slug = url_title($this->input->post('title'), 'dash', TRUE);
$slugcount = $this->Posts_model->slug_count($slug);
if ($slugcount > 0) {
$slug = $slug."-".$slugcount;
}
} else {
$slug = $this->input->post('slug');
}
// Upload image
$config['upload_path'] = './assets/img/posts';
$config['allowed_types'] = 'jpg|png';
$config['max_size'] = '2048';
$this->load->library('upload', $config);
if(!$this->upload->do_upload()){
$errors = array('error' => $this->upload->display_errors());
$post_image = $this->input->post('postimage');
} else {
$data = array('upload_data' => $this->upload->data());
$post_image = $_FILES['userfile']['name'];
}
if ($this->form_validation->run()) {
$this->Posts_model->update_post($id, $post_image, $slug);
$this->session->set_flashdata('post_updated', 'Your post has been updated');
redirect('/' . $slug);
} else {
redirect('/posts/edit/' . $slug);
}
}
I am almost certain the problem is this line: redirect('/posts/edit/' . $slug); but I have not been able to find a viable alternative.
Using $this->edit($id) instead of redirect('/posts/edit/' . $slug); does not work either. I wish it would, because I want to keep the code DRY.
What shall I change?
Edit. I did this:
if ($this->form_validation->run()) {
$this->Posts_model->update_post($id, $post_image, $slug);
$this->session->set_flashdata('post_updated', 'Your post has been updated');
redirect('/' . $slug);
} else {
$this->form_validation->run();
$this->session->set_flashdata('errors', validation_errors());
var_dump($this->session->flashdata('errors'));
//redirect('/posts/edit/' . $slug);
}
The var_dump($this->session->flashdata('errors')); returns all the validation errors.
I wish to add the class has-error to the form-group and append <p class="error-message">The Title field is required.</p>.
<div class="form-group has-error">
<input type="text" name="title" id="title" class="form-control error" placeholder="Title" data-rule-required="true" value="Learn to code with us" aria-invalid="true">
<p class="error-message">The Title field is required.</p>
</div>
You have 3 options:
Use flash data in update method on failure (you are already using it on success). Simply assign the errors to a flash data variable and get it after you redirect back to edit.
Combine edit and update methods (most common for non-ajax usage).
Use ajax and return json encoded strings for errors or success messages.
Option 2:
This option also solves the potential authentication issue pointed out in the comments.
Please read the comments embedded in the code.
public function edit($id) {
// Only logged in users can edit posts
if (!$this->session->userdata('is_logged_in')) {
redirect('login');
}
$data['post'] = $this->Posts_model->get_post($id);
if ($this->session->userdata('user_id') == $data['post']->author_id) {
show_error('Access denied'); // function exits
}
if ($_POST) {
$this->form_validation->set_rules('title', 'Title', 'required', array('required' => 'The %s field can not be empty'));
$this->form_validation->set_rules('desc', 'Short description', 'required', array('required' => 'The %s field can not be empty'));
$this->form_validation->set_rules('body', 'Body', 'required', array('required' => 'The %s field can not be empty'));
$this->form_validation->set_error_delimiters('<p class="error-message">', '</p>');
//$id = $this->input->post('id'); not required anymore
$config['upload_path'] = './assets/img/posts';
$config['allowed_types'] = 'jpg|png';
$config['max_size'] = '2048';
$this->load->library('upload', $config);
if ($this->form_validation->run() && $this->upload->do_upload()) {
// always use the name from the upload lib
// sometimes it changes it in case of duplicates (read docs for more)
$post_image = $this->upload->data('file_name');
// doesn't make sense with title validation rule, this will always be true to get
// passed validation
if (!empty($this->input->post('title'))) {
$slug = url_title($this->input->post('title'), 'dash', TRUE);
$slugcount = $this->Posts_model->slug_count($slug);
if ($slugcount > 0) {
$slug = $slug . "-" . $slugcount;
}
} else {
$slug = $this->input->post('slug');
}
$this->Posts_model->update_post($id, $post_image, $slug);
$this->session->set_flashdata('post_updated', 'Your post has been updated');
redirect('/' . $slug);
} else {
$data['errors'] = validation_errors() . $this->upload->display_errors();
}
}
$data = $this->Static_model->get_static_data();
$data['pages'] = $this->Pages_model->get_pages();
$data['categories'] = $this->Categories_model->get_categories();
$data['posts'] = $this->Posts_model->sidebar_posts($limit = 5, $offset = 0);
$data['tagline'] = 'Edit the post "' . $data['post']->title . '"';
$this->load->view('partials/header', $data);
$this->load->view('edit-post');
$this->load->view('partials/footer');
}
What I would do in this scenario is merge both methods into a single method relying on the validation to know if I am saving the entry or not.
your code would look something like this:
public function edit($id) {
// Only logged in users can edit posts
if (!$this->session->userdata('is_logged_in')) {
redirect('login');
}
$Post = $this->Posts_model->get_post($id);
// user does not own the post, redirect
if ($this->session->userdata('user_id') !== $Post->author_id) {
redirect('/' . $id);
}
// Form data validation rules
$this->form_validation->set_rules('title', 'Title', 'required', array('required' => 'The %s field can not be empty'));
$this->form_validation->set_rules('desc', 'Short description', 'required', array('required' => 'The %s field can not be empty'));
$this->form_validation->set_rules('body', 'Body', 'required', array('required' => 'The %s field can not be empty'));
$this->form_validation->set_error_delimiters('<p class="error-message">', '</p>');
// if validation fails, or the form isn't submitted
if ($this->form_validation->run() === false ) {
$data = $this->Static_model->get_static_data();
$data['pages'] = $this->Pages_model->get_pages();
$data['categories'] = $this->Categories_model->get_categories();
$data['posts'] = $this->Posts_model->sidebar_posts($limit=5, $offset=0);
$data['post'] = $Post;
$data['tagline'] = 'Edit the post "' . $data['post']->title . '"';
$this->load->view('partials/header', $data);
$this->load->view('edit-post');
$this->load->view('partials/footer');
}else{
// Update slug (from title)
if (! empty($this->input->post('title'))) {
$slug = url_title($this->input->post('title'), 'dash', TRUE);
$slugcount = $this->Posts_model->slug_count($slug);
if ($slugcount > 0) {
$slug = $slug."-".$slugcount;
}
} else {
$slug = $this->input->post('slug');
}
// Upload image
$config['upload_path'] = './assets/img/posts';
$config['allowed_types'] = 'jpg|png';
$config['max_size'] = '2048';
$this->load->library('upload', $config);
if(!$this->upload->do_upload()){
$errors = array('error' => $this->upload->display_errors());
$post_image = $this->input->post('postimage');
} else {
$data = array('upload_data' => $this->upload->data());
$post_image = $_FILES['userfile']['name'];
}
$this->Posts_model->update_post($id, $post_image, $slug);
$this->session->set_flashdata('post_updated', 'Your post has been updated');
redirect('/' . $slug);
}
}
and you don't have to implement the update separately, you just post to /edit/$id instead of /update/$id ... this is a rough example, your slug checking (which I haven't touched upon) is not the correct way to do it, if it passes the validation the title is already filled since it's set to required so I guess you meant if (! empty(slug) ), but again in your else you are setting the slug directly from user input, so I would add it to the validation and make sure it's unique in the database except for the $id that's being edited currently.
Again, this is the result of copy & paste from your original code i might have missed something so give it a good read to make sure nothing is missing and include the validation errors in the data you are passing to the view.
I have managed to get the desired result using set_flashdata() as suggested by #Alex
In the controller I have:
public function update() {
// Form data validation rules
$this->form_validation->set_rules('title', 'Title', 'required', array('required' => 'The %s field can not be empty'));
$this->form_validation->set_rules('desc', 'Short description', 'required', array('required' => 'The %s field can not be empty'));
$this->form_validation->set_rules('body', 'Body', 'required', array('required' => 'The %s field can not be empty'));
$this->form_validation->set_error_delimiters('<p class="error-message">', '</p>');
$id = $this->input->post('id');
// Update slug (from title)
if (!empty($this->input->post('title'))) {
$slug = url_title($this->input->post('title'), 'dash', TRUE);
$slugcount = $this->Posts_model->slug_count($slug);
if ($slugcount > 0) {
$slug = $slug."-".$slugcount;
}
} else {
$slug = $this->input->post('slug');
}
// Upload image
$config['upload_path'] = './assets/img/posts';
$config['allowed_types'] = 'jpg|png';
$config['max_size'] = '2048';
$this->load->library('upload', $config);
if(!$this->upload->do_upload()){
$errors = array('error' => $this->upload->display_errors());
$post_image = $this->input->post('postimage');
} else {
$data = array('upload_data' => $this->upload->data());
$post_image = $_FILES['userfile']['name'];
}
if ($this->form_validation->run()) {
$this->Posts_model->update_post($id, $post_image, $slug);
$this->session->set_flashdata('post_updated', 'Your post has been updated');
redirect('/' . $slug);
} else {
$this->form_validation->run();
$this->session->set_flashdata('errors', validation_errors());
redirect('/posts/edit/' . $slug);
}
}
In the view:
<?php if ($this->session->flashdata('errors')) {
$errors = $this->session->flashdata('errors');
echo '<div class="error-group alert alert-warning alert-dismissible">' . "\n";
echo '<button type="button" class="close" data-dismiss="alert">×</button>' . "\n";
echo $errors;
echo '<p class="error-message">We have restored the post.</p>';
echo '</div>';
} ?>

codeigniter : update function model and controller

I don't know what I am doing wrong in this.
If anyone could help!
cause i have tried all solutions...
also undefined variable $data error
/************************/
public function edit_stud($student_id)
{
$this->form_validation->set_rules('full_name', 'full_name', 'required');
$this->form_validation->set_rules('father_name', 'father_name', 'required');
$this->form_validation->set_rules('roll_no', 'roll_no', 'required');
if($this->form_validation->run() === FALSE)
{
$data['student']= $this ->stud_model->update_student($student_id, $data);
$this->load->view('edit_form' , $data);
}
else
{
$full_name = $this->input->post('full_name', true);
$father_name = $this->input->post('father_name', true);
$roll_no = $this->input->post('roll_no', true);
$data = array(
'full_name'=>$full_name ,
'father_name'=>$father_name ,
'roll_no'=>$roll_no,
);
$student_id = $this->stud_model->update_student($student_id,$data);
redirect('/stud/edit_stud/'.student_id);
}
}
//***********************Model in CI***//////////////
public function update_student($student_id,$data)
{
$this->db->set($this->table_name,$student_id, $data);
return $this->db->update_id();
}
$data is never defined in the first part of your IF statement.
In particular this line
$data['student'] = $this->stud_model->update_student($student_id, $data);
is the problem. If the form validation is false, you don't want to update the student. Remove that line, and everything should be fine.
Unless you do want to update student even if the validation fails (This is a bad idea, IMO). Then your controller would look like this
public function edit_stud($student_id) {
$this->form_validation->set_rules('full_name', 'full_name', 'required');
$this->form_validation->set_rules('father_name', 'father_name', 'required');
$this->form_validation->set_rules('roll_no', 'roll_no', 'required');
$full_name = $this->input->post('full_name', true);
$father_name = $this->input->post('father_name', true);
$roll_no = $this->input->post('roll_no', true);
$data = array(
'full_name' => $full_name ,
'father_name' => $father_name ,
'roll_no' => $roll_no,
);
$student_id = $this->stud_model->update_student($student_id, $data);
if($this->form_validation->run() === FALSE)
$this->load->view('edit_form' , $data);
} else {
redirect('/stud/edit_stud/'.student_id);
}
}
Thanks for suggestions i have solved the problem i was having
in my code i did some renditions...posting the correct answer for
anyone else, having same sort of problem.
this is the controller code.
/*****controller code*****/
/***************************edit student ******************************/
public function edit_stud($student_id)
{
$this->form_validation->set_rules('full_name', 'full_name', 'required');
$this->form_validation->set_rules('father_name', 'father_name', 'required');
$this->form_validation->set_rules('roll_no', 'roll_no', 'required');
if($this->form_validation->run() === FALSE)
{
$data['student']= $this ->stud_model->get_student($student_id);
$this->load->view('edit_form' , $data);
}
else
{
$full_name = $this->input->post('full_name', true);
$father_name = $this->input->post('father_name', true);
$roll_no = $this->input->post('roll_no', true);
$data = array(
'full_name'=>$full_name ,
'father_name'=>$father_name ,
'roll_no'=>$roll_no,
);
$student_id = $this->stud_model->update_student($student_id,$data);
redirect('/stud/edit_stud/'.student_id);
}
}
/************************delete student ************************/
public function delete_stud($student_id)
{
$this ->stud_model->delete_student($student_id);
redirect('/stud/');
}
/***********************model code *******/
/************to get student id*********/
public function get_student($student_id)
{
$this->db->select('*');
$this->db->from($this->table_name);
$this->db->where('id',$student_id);
$query = $this->db->get();
if($query->num_rows() >0)
{
$return = $query->row();
}
else
{
$return = 0;
}
$query->free_result();
return $return;
}
/*****************update function***********************/
public function update_student($id, $data)
{
$where = array('id' => $id);
$this->db->update($this->table_name, $data, $where);
}

Captcha value different with session user data

I'm trying to create captcha, the image is shown as expected, but when i pass into controller why the string that i input is different with session user data that i set in earlier.
PFB my code.
View.
<?php echo $captcha_img;?>
<input type="text" id="captcha" name="captcha" placeholder="Input Code Above">
<?php echo form_error('captcha', '<p class="field_error">', '</p>');?>
Controller (config)
public function captcha_config() {
$vals = array(
'img_path' => './assets/files/captcha/',
'img_url' => base_url().'assets/files/captcha/',
'img_width' => 150,
'img_height' => 30
);
$cap = create_captcha($vals);
$image = $cap['image'];
$this->session->set_userdata('capt',$cap['word']);
//$data['captcha_img'] = $cap['image'];
return $image;
}
Controller (Index)
public function index() {
if ($this->session->userdata('login') == TRUE)
{
redirect('Buser');
}
else
{
$data['title'] = 'Dashboard';
$data['subtitle'] = 'Log In';
$this->captcha_config();
$data['captcha_img'] = $this->captcha_config();
$this->load->view('Backend/login', $data);
}
Controller (Process)
public function process_login() {
$data['title'] = 'Dashboard';
$data['subtitle'] = 'Log In';
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
$this->form_validation->set_rules('captcha', 'Captcha', 'required' );
$this->captcha_config();
$data['captcha_img'] = $this->captcha_config();
if ($this->form_validation->run() == TRUE)
{
$username = $this->input->post('username');
$password = $this->input->post('password');
$captcha = $this->input->post('captcha');
echo $captcha;
echo "<br>";
echo $this->session->userdata('capt');
}
}
result:
Drd27VZE <--- this one is the captcha
VzU90odU <--- this one is the session user data 'capt'
I've been trying using with separate code (example that i got from google) it works, but i don't know why it's not working with this code.
you can create a captcha function in helper
Helper
function generate_captcha()
{
$options = array(
'img_path' => 'img/captcha/',
'img_url' => base_url().'img/captcha/',
'img_width' => '150',
'img_height'=> '50',
'expiration'=> 3600,
'word' => generate_random_password(4)
);
return create_captcha($options);
}
function generate_random_password( $max_length = 8 )
{
$pass = '';
$dict = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$dict_size = strlen($dict);
for($i = 0;$i<$max_length;$i++){
$pass .= $dict[rand(0,$dict_size-1)];
}
return strtoupper($pass);
}
In your view, you call a generate_captcha if the user put a wrong user ou pass
<?php if( ! empty( $attempts_number ) && ((int)$attempts_number >= 3) ) { ?>
<?php $captcha = generate_captcha(); ?>
<?php $this->session->set_userdata(array(
'captchaword' => $captcha['word']
)); ?>
<?php echo $captcha['image']; ?>
<label><?php echo $this->lang->line('captcha_text'); ?>:</label>
<?php echo form_input(array('class'=>'required','maxlength'=>4,'name'=>'captcha'));?>
<?php } ?>
Finally i solve my problem,
problem when i create function for captcha i don't have to call again in the process function
public function process_login() {
$data['title'] = 'Dashboard';
$data['subtitle'] = 'Log In';
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
$this->form_validation->set_rules('captcha', 'Captcha', 'required' );
**$this->captcha_config(); <---- I Remove this one
$data['captcha_img'] = $this->captcha_config(); <---- and also remove this one**
if ($this->form_validation->run() == TRUE)
{
$username = $this->input->post('username');
$password = $this->input->post('password');
$captcha = $this->input->post('captcha');
echo $captcha;
echo "<br>";
echo $this->session->userdata('capt');
}
}

CodeIgniter upload function, sometime not works

I have problem with codeigniter upload function.
The function works well, but sometimes didn't work and without any error info.
snippet in controller
...
function add_process() {
$data['title'] = anchor('event/','<b>EVENT</b>', array('class' => 'back'));
$data['subtitle'] = ' / Add Event';
$data['main_view'] = 'event/event_form';
$data['form_action'] = site_url('event/add_process');
$this->form_validation->set_rules('eventName', 'Event Name', 'required');
$this->form_validation->set_rules('eventDate', 'Event Date', 'required');
if (empty($_FILES['eventImage']['name'])){
$this->form_validation->set_rules('eventImage', 'Event Image', 'required');
}
if ($this->form_validation->run() == TRUE) {
$config['upload_path'] = './images/event/';
$config['allowed_types'] = 'jpg|jpeg|png';
//$config['max_width'] = '3000';
//$config['max_height'] = '3000';
$this->load->library('upload', $config);
$this->upload->do_upload('eventImage');
$eventImage = $this->upload->data();
$event = array( 'eventName' => $this->input->post('eventName'),
'eventDate' => date('Y-m-d', strtotime($this->input->post('eventDate'))),
'eventDescriptions' => $this->input->post('eventDescriptions'),
'eventImage' => 'images/event/'.$eventImage['file_name'],
'isActive' => $this->input->post('isActive')
);
$this->Event_model->add($event);
$this->session->set_flashdata('message', '1 record was successfully added!');
redirect('event/add');
} else {
$this->load->view('admin/admin_main', $data);
}
}
...
could you tell please, what am i missing here?
Replace this
$this->Event_model->add($event);
$this->session->set_flashdata('message', '1 record was successfully added!');
redirect('event/add');
to this
if ($this->Event_model->add($event)) {
$this->session->set_flashdata('message', '1 record was successfully added!');
redirect('event/add');
}

error updating data in codeigniter

i getting error when i want to update data. I am a newbie in Codeigniter and couldn't really figure out how to solve this. error display
Severity: Notice
Message: Undefined variable: tanggal, judul_berita, content
Filename: admin/berita.php
model
function get_berita($limit = 1, $offset = 0)
{
$this->db->order_by('id_berita','asc');
$data = $this->db->get($this->tbl_berita, $limit, $offset);
return $data->result();
}
function update_berita($id_berita,$data, $limit = 1, $offset = 0)
{
$this->db->where('id_berita', $id_berita);
$this->db->update($this->tbl_berita, $data);
$data = $this->db->get_where($this->tbl_berita, array('id_berita' => $id_berita), $limit, $offset);
return $data->result();
}
controller
function edit_berita()
{
$this->form_validation->set_rules('tanggal', 'Tanggal', 'required');
$this->form_validation->set_rules('judul_berita', 'Judul Berita', 'required');
$this->form_validation->set_rules('content', 'Content', 'required');
$id_berita = $this->uri->segment(4);
if ($this->form_validation->run() == FALSE)
{
$data['id_berita'] = $id_berita;
$data['tanggal'] = $tanggal; //line error
$data['judul_berita'] = $judul_berita; //line error
$data['content'] = $content; // line error
$this->data['contents'] = $this->load->view('admin/berita/edit_berita', $data, true);
$this->data['orang'] = $this->mlogin->dataPengguna($this->session->userdata('username'));
$this->load->view('template/wrapper/admin/wrapper_ukm',$this->data);
}else{
$this->load->model('mberita');
$data = array(
'id_berita' => $id_berita,
'tanggal' => $this->input->post('tanggal'),
'judul_berita' => $this->input->post('judul_berita'),
'content' => $this->input->post('content')
);
$this->mberita->update_berita($id_berita,$data);
redirect(site_url('admin/berita'));
}
}
please help me what to do. thank you

Categories