#StackBounty: #codeigniter #codeigniter-3 Need understanding $config["uri_segment"] related code in CodeIgniter

Bounty: 50

Hey CodeIgniter developers I am new in codeIgniter please see my code related to pagination. Pagination is working fine. I just need your help to understand few lines of code, please see the commented lines in code where I just need your help to understand it.

public function example1() {
        $config = array();
        $config["base_url"] = base_url() . "welcome/example1";
        $config["total_rows"] = $this->services->record_count();
        $config["per_page"] = 10;
        $config["uri_segment"] = 3; // Need help on this line
        $config["next_link"] = '>';
        $config["prev_link"] = '<';

        $this->pagination->initialize($config);
        // Need help on this if condition blocks
        if ($this->uri->segment(3)) {
            $page = ($this->uri->segment(3));
        } else {
            $page = 1;
        }
        $data["results"] = $this->services->fetchServicesByPagination($config["per_page"], $page);
        $data["links"] = $this->pagination->create_links();

        $this->load->view("example1", $data);
    }


Get this bounty!!!

#StackBounty: #php #mvc #codeigniter PHP Edit Volunteer Group Form

Bounty: 50

I have a PHP CodeIgniter website that collects volunteer registrations. One thing I have noticed is that the controllers are getting really big. The controllers have many methods, and each method is fairly long. I believe this could be a code smell, and I would like some help and advice on how to refactor the code.

The website is in production and too big to post all the code. I will pick a sample page to post here so you can get an idea. I’m looking for broad feedback on how to improve the organization of the code. For example:

  • Idea 1 – Should I move some of this code to a new layer between the controller and the model? I’ve seen this recommended in some places. I believe it’s called a domain layer.
  • Idea 2 – Should I break this entire method (and other big methods) off into their own classes? Since I’m using CodeIgniter, I guess these would be library classes?
  • Idea 3 – Should I make more use of private methods within the giant controller class? Won’t shrink the size of the controller, but might make some of the code more readable. Or maybe not, since I’d be scrolling all over the page to find code, instead of just reading it linearly.
  • Idea 4 – Should I try to move more code into the models? My models are a similar size to the controllers.
  • Idea 5 – The code works and I (the only developer) can read it just fine. Should I just leave it alone? YAGNI? Keep complexity down?
  • I have a lot of controller methods that start out with form validation code. What is the best way to handle that?
  • Bonus question: What are good ways to test a website? I currently use iMacros browser plugin and run scripts that simulate typing, mouse clicks, submitting forms, clicking links, etc. I have heard of unit testing but am not sure where to start with that. Is it worth it to write a bunch of unit tests?
  • Other ideas/feedback?

Screenshot

enter image description here

Code

public function edit_group($group_id_and_text = NULL)
{
    $this->data = set_page_title('Edit Group', $this->data);

    $this->data = $this->_get_group_data_or_throw_error_page($group_id_and_text, $this->data, '/managers/edit_group/');

    $this->data['list_of_shifts'] = $this->shift_model->get_race_shifts_with_enrolled_plus_groups_fields($this->data['race']['race_id']);

    $this->data['list_of_group_shifts'] = $this->group_shift_model->get_group_shifts_for_group($this->data['group']['group_id']);

    // output format is $shift_id => $number_promised
    $this->data['list_of_group_shifts_as_list'] = $this->group_shift_model->get_group_shifts_as_list($this->data['group']['group_id'], $this->data['race']['race_id']);

    $this->data['list_of_shifts_to_highlight'] = highlight_shifts_that_need_more_groups($this->data['list_of_shifts']);

    $this->data['list_of_volunteers_with_shifts'] = $this->volunteer_shift_model->get_volunteers_by_race_and_group($this->data['race']['race_id'], $this->data['group']['group_id']);

    $this->data['list_of_volunteers_without_shifts'] = $this->volunteer_shift_model->get_volunteers_with_no_shifts_filter_by_group($this->data['race']['race_id'], $this->data['group']['group_id']);

    $this->data['list_of_volunteers'] = array_merge($this->data['list_of_volunteers_with_shifts'], $this->data['list_of_volunteers_without_shifts']);

    $this->form_validation->set_rules('group_name', 'Group Name', 'trim|required|max_length[200]');

    $this->form_validation->set_rules('shift_id[]', 'Volunteer Shift', 'trim|valid_volunteer_group_shift_for_admin[' . $this->data['race']['race_id'] . ']');

    $this->form_validation->set_rules('group_notes', 'Group Notes', 'trim|max_length[1000]');
    $this->form_validation->set_rules('group_send_reminder_emails', 'Reminder Emails', 'trim|required|in_list[0,1]');
    $this->form_validation->set_rules('fix_shifts', 'Fix Volunteer Shifts', 'trim|in_list[1]');
    $this->form_validation->set_rules('email_group_leader', 'Email Group Leader', 'trim|in_list[1]');
    $this->form_validation->set_rules('delete_group', 'Delete Group', 'trim|in_list[1]');
    $this->form_validation->set_rules('delete_group_members', 'Delete Group Members', 'trim|in_list[1]');
    $this->form_validation->set_rules('group_firm', 'Mark As Firm', 'trim|in_list[1]');

    // Note: SQL WHERE is case insensitive, which is good in this case
    $this->data['group_for_duplicate_check'] = $this->group_model->get_group_by_race_and_group_name(
        $this->data['race']['race_id'],
        $this->input->post('group_name')
    );

    if ($this->form_validation->run() === FALSE)
    {
        load_page_with_event_nav('managers/edit_group', $this->data);
    }
    elseif ( $this->data['group_for_duplicate_check'] && $this->data['group_for_duplicate_check']['group_id'] != $this->data['group']['group_id'] )
    {
        add_message('error', 'A group with this name already exists. <a href="/managers/edit_group/' . $this->data['group_for_duplicate_check']['group_uri'] . '">Click here</a> to view and edit the existing group.');

        load_page_with_event_nav('managers/edit_group', $this->data);
    }
    else
    {
        $group_leader_volunteer_id = $this->data['group']['group_leader_volunteer_id'];

        // Putting delete_group_members before delete_group so that the soft deleted volunteers keep their group_id. Will be helpful if I have to undo the soft delete.
        if ( $this->input->post('delete_group_members') )
        {
            $volunteer_ids = $this->data['list_of_volunteers'];

            if ( $volunteer_ids ) {         
                $volunteer_ids = sql_make_list_from_sql_result_array($volunteer_ids, 'volunteer_id');

                $volunteer_ids = mv_eliminate_duplicates($volunteer_ids);

                $this->volunteer_model->soft_delete_volunteer($volunteer_ids);

                add_message('success', '"' . html_escape($this->data['group']['group_name']) . '"'s group members were successfully deleted from the group AND the volunteer database.');
            }
        }

        if ( $this->input->post('delete_group') )
        {
            $this->group_model->soft_delete_groups($this->data['group']['group_id']);

            // If group_leader_volunteer_id got deleted because the volunteer got soft deleted, AND the group is getting deleted, restore the group_leader_volunteer_id so that email_list can display deleted group leaders.
            $this->group_model->set_group_leader($this->data['group']['group_id'], $group_leader_volunteer_id);

            add_message('success', '"' . html_escape($this->data['group']['group_name']) . '" was successfully deleted.');
        }
        else
        {
            $this->group_model->edit_group($this->data);

            // refresh some variables needed down here
            $this->data['group'] = $this->group_model->get_group_by_id($this->data['group']['group_id']);

            $this->data['volunteer'] = $this->volunteer_model->get_volunteer_by_id($this->data['group']['group_leader_volunteer_id']);

            $this->data['list_of_group_shifts'] = $this->group_shift_model->get_group_shifts_for_group($this->data['group']['group_id']);

            $shifts_to_compare = $this->data['list_of_group_shifts_as_list'];

            /*
                PHP's array compare is extremely loose.
                1) It compares array contents, not references.
                2) It compares across types. For example, 0 and '0' are seen as the same thing.
                3) The order of the array keys doesn't matter, so we don't need to sort them.
            */
            if ( $this->input->post('shift_id') != $shifts_to_compare )
            {
                $this->group_shift_model->hard_delete_groups_shifts($this->data['group']['group_id']);

                foreach ( $_POST['shift_id'] as $shift_id => $value )
                {
                    if ( $value != 0 )
                    {
                        $this->group_shift_model->add_shift(
                            $this->data['group']['group_id'],
                            $shift_id,
                            $value,
                            $this->data
                        );
                    }
                }
            }

            // refresh again
            $this->data['list_of_group_shifts'] = $this->group_shift_model->get_group_shifts_for_group($this->data['group']['group_id']);

            $list_of_group_shifts = sql_make_list_from_sql_result_array($this->data['list_of_group_shifts'], 'shift_id');

            // Make sure the group leader is enrolled in all the group's shifts. This is important so that the group leader receives the volunteer instructions for each of this group's shifts.
            if ( $this->data['volunteer'] )
            {
                foreach ( $list_of_group_shifts as $key => $shift_id )
                {
                    $shift = $this->volunteer_shift_model->get_shift_by_volunteer_id_and_shift_id($this->data['volunteer']['volunteer_id'], $shift_id);

                    if ( ! $shift )
                    {
                        $this->volunteer_shift_model->add_shift(
                            $this->data['volunteer']['volunteer_id'],
                            $shift_id,
                            $this->data['auth']['manager']['manager_id']
                        );
                    }
                }
            }

            add_message('success', '"<a href="/managers/edit_group/' . $this->data['group']['group_uri'] . '">' . html_escape($this->data['group']['group_name']) . '</a>" was successfully edited.');

            if ( $this->input->post('fix_shifts') == 1 )
            {
                // ****** FIX_SHIFTS_REMOVE ******
                foreach ( $this->data['list_of_volunteers_with_shifts'] as $key => $volunteer_shift )
                {
                    if ( !in_array($volunteer_shift['shift_id'], $list_of_group_shifts) )
                    {
                        $this->volunteer_shift_model->hard_delete_one_volunteer_one_shift($volunteer_shift['volunteer_id'], $volunteer_shift['shift_id']);
                    }
                }

                // ****** FIX_SHIFTS_ADD ******
                $this->data['list_of_volunteers_not_joined_with_volunteer_shifts'] = $this->volunteer_model->get_volunteers_by_race_and_group($this->data['race']['race_id'], $this->data['group']['group_id']);

                $this->data['list_of_volunteer_shifts_for_this_race'] = $this->volunteer_shift_model->get_volunteers_by_race_order_by_name($this->data['race']['race_id']);

                foreach ( $this->data['list_of_volunteers_not_joined_with_volunteer_shifts'] as $key => $volunteer )
                {
                    foreach ( $list_of_group_shifts as $key => $shift_id )
                    {
                        $shift_already_exists = sql_search_result_array_contains_key1_value1_key2_value2(
                            $this->data['list_of_volunteer_shifts_for_this_race'],
                            'volunteer_id',
                            $volunteer['volunteer_id'],
                            'shift_id',
                            $shift_id
                        );

                        if ( ! $shift_already_exists )
                        {
                            $this->volunteer_shift_model->add_shift(
                                $volunteer['volunteer_id'],
                                $shift_id,
                                $this->data['auth']['manager']['manager_id']
                            );
                        }
                    }
                }

                $this->group_shift_model->fix_more_enrolled_vols_than_estimated_vols($this->data['group']['group_id']);
            }

            if ( $this->input->post('email_group_leader') == 1 )
            {
                // return true for non-NULL, non-zero
                if ( $this->data['group']['group_leader_volunteer_id'] )
                {
                    $this->data['list_of_this_groups_shifts'] = $this->shift_model->get_group_shifts($this->data['group']['group_id']);

                    send_group_confirmation_email($this->data, $this->data['volunteer']['volunteer_email']);

                    add_message('success', 'Also, we e-mailed the group leader a group confirmation e-mail.');
                }
                else
                {
                    add_message('error', 'You requested that we send a confirmation e-mail, but we were unable to because a volunteer group leader was not provided.');
                }
            }
        }

        $this->shift_model->recalculate_shift_stats($this->data['race']['race_id']);

        redirect_and_die('/managers/group_report/' . $this->data['race']['race_uri']);
    }
}


Get this bounty!!!

#StackBounty: #beginner #php #security #authentication #codeigniter Codeigniter 3 Registration and Login System

Bounty: 50

I am working on a basic blog application in Codeigniter 3.1.8 and Bootstrap 4.

The application allows Registration and Login. I have concerns about the security level of the Registration system I have put together.

The Register controller:

class Register extends CI_Controller {
    public function __construct()
    {
        parent::__construct();
    }

    public function index() {
        $data = $this->Static_model->get_static_data();
        $data['pages'] = $this->Pages_model->get_pages();
        $data['tagline'] = 'Want to write for ' . $data['site_title'] . '? Create an account.';
        $data['categories'] = $this->Categories_model->get_categories();

        $this->form_validation->set_rules('first_name', 'First name', 'required');
        $this->form_validation->set_rules('last_name', 'Last name', 'required');
        $this->form_validation->set_rules('email', 'Email', 'required|trim|valid_email');
        $this->form_validation->set_rules('password', 'Password', 'required|min_length[6]');
        $this->form_validation->set_rules('cpassword', 'Confirm password', 'required|matches[password]');
        $this->form_validation->set_rules('terms', 'Terms and Conditions', 'required', array('required' => 'You have to accept the Terms and Conditions'));
        $this->form_validation->set_error_delimiters('<p class="error-message">', '</p>');

        // If validation fails
        if ($this->form_validation->run() === FALSE) {
            $this->load->view('partials/header', $data);
            $this->load->view('auth/register');
            $this->load->view('partials/footer');
        } else {
            // If the provided email does not already
            // exist in the authors table, register user
            if (!$this->Usermodel->email_exists()) {
                // Encrypt the password
                $enc_password = md5($this->input->post('password'));

                // Give the first author admin privileges
                if ($this->Usermodel->get_num_rows() < 1) {
                    $active = 1;
                    $is_admin = 1;
                } else {
                    $active = 0;
                    $is_admin = 0;
                }

                // Register user
                $this->Usermodel->register_user($enc_password, $active, $is_admin);

                if ($this->Usermodel->get_num_rows() == 1) {
                    $this->session->set_flashdata('user_registered', "You are now registered as an admin. You can sign in");
                } else {
                    $this->session->set_flashdata('user_registered', "You are now registered. Your account needs the admin's aproval before you can sign in.");
                }
                redirect('login');
            } else {
                // The user is already registered
                $this->session->set_flashdata('already_registered', "The email you provided already exists in our database. Please login.");
                redirect('login');
            }
        }
    }
}

The Usermodel model:

class Usermodel extends CI_Model {

    public function email_exists() {    
        $query = $this->db->get_where('authors', ['email' => $this->input->post('email')]);
        return $query->num_rows() > 0;
    }

    public function get_num_rows() {
        $query = $this->db->get('authors');
        return $query->num_rows(); 
    }

    public function getAuthors(){
        $query = $this->db->get('authors');
        return $query->result();
    }

    public function deleteAuthor($id) {
        return $this->db->delete('authors', array('id' => $id));
    }

    public function activateAuthor($id) {
        $author = null;
        $updateQuery = $this->db->where(['id' => $id, 'is_admin' => 0])->update('authors', array('active' => 1));
        if ($updateQuery !== false) {
        $authorQuery = $this->db->get_where('authors', array('id' => $id));
        $author = $authorQuery->row();
        }
        return $author;
    }

    public function deactivateAuthor($id) {
        $author = null;
        $updateQuery = $this->db->where(['id' => $id, 'is_admin' => 0])->update('authors', array('active' => 0));
        if ($updateQuery !== false) {
            $authorQuery = $this->db->get_where('authors', array('id' => $id));
            $author = $authorQuery->row();
        }
        return $author;
    }

    public function register_user($enc_password, $active, $is_admin) {
        // User data
        $data = [
            'first_name' => $this->input->post('first_name'),
            'last_name' => $this->input->post('last_name'),
            'email' => $this->input->post('email'),
            'password' => $enc_password,
            'register_date' => date('Y-m-d H:i:s'),
            'active' => $active,
            'is_admin' => $is_admin
        ];
        return $this->db->insert('authors', $data);
    }

    public function user_login($email, $password)
    {
        $query = $this->db->get_where('authors', ['email' => $email, 'password' => md5($password)]);
        return $query->row();
    }
}

UPDATE:

I have decided to post the login() method, from the Login controller, as changing the Register class would require changing the login accordingly:

public function login() {  
    $this->form_validation->set_rules('email', 'Email', 'required|trim|valid_email');
    $this->form_validation->set_rules('password', 'Password', 'required|trim');
    $this->form_validation->set_error_delimiters('<p class="error-message">', '</p>');
    if ($this->form_validation->run()) {
      $email = $this->input->post('email');
      $password = $this->input->post('password');
      $this->load->model('Usermodel');
      $current_user = $this->Usermodel->user_login($email, $password);
        // If we find a user
      if ($current_user) {
        // If the user found is active
        if ($current_user->active == 1) {
          $this->session->set_userdata(
           array(
            'user_id' => $current_user->id,
            'user_email' => $current_user->email,
            'user_first_name' => $current_user->first_name,
            'user_is_admin' => $current_user->is_admin,
            'user_active' => $current_user->active,
            'is_logged_in' => TRUE
            )
           );
          // After login, display flash message
          $this->session->set_flashdata('user_signin', 'You have signed in');
          //and redirect to the posts page
          redirect('/dashboard');  
        } else {
          // If the user found is NOT active
          $this->session->set_flashdata("login_failure_activation", "Your account has not been activated yet.");
          redirect('login'); 
        }
      } else {
        // If we do NOT find a user
        $this->session->set_flashdata("login_failure_incorrect", "Incorrect email or password.");
        redirect('login'); 
      }
    }
    else {
      $this->index();
    }
  }

Looking for feedback and improvement ideas.


Get this bounty!!!

#StackBounty: #php #codeigniter Codeigniter 3 micro-blogging application

Bounty: 50

I am working on a basic blog application in Codeigniter 3.1.8 and Bootstrap 4.

The application allows Registration (as an author), Login, adding Categories and Posts.

I have created an installation process for the application: after creating a database and providing its credentials to the application/config/database.php file, you can run the Install controller which will create all the necessary tables:

class Install extends CI_Controller {
    public function __construct()
    {
        parent::__construct();
    }

    public function index(){
        // Create all the database tables if there are none
        // by redirecting to the Migrations controller
        $tables = $this->db->list_tables();
        if (count($tables) == 0) {
            redirect('migrate');
        } else {
            redirect('/');
        }
    }
}

After that, you can register as an author. Being the first registered author, you are also an admin, meaning that your author account does not require activation (the is_admin column has a value of 1 for you).

All the future authors will need their accounts activated by you in order to publish articles (posts).

It is a rather ambitious project, although I did not start it with great plans in mind. I just wanted to learn Codeigniter 3. You can see it on my GitHub account.

There are a few possible issues:

  1. The application does not use HMVC, but “classic” MVC.
  2. It does not have a clear separation between its front and its back (admin)
  3. I want to add a theming feature and I kinda got stuck with it; I don’t know what approach to use.
  4. My controllers may be a over-coded.

Here is the Posts controller:

 class Posts extends CI_Controller {

    public function __construct()
    {
        parent::__construct();
    }

    private function _initPagination($path, $totalRows, $query_string_segment = 'page') {
    //load and configure pagination 
        $this->load->library('pagination');
        $config['base_url'] = base_url($path);
        $config['query_string_segment'] = $query_string_segment; 
        $config['enable_query_strings'] =TRUE;
        $config['reuse_query_string'] =TRUE;
        $config['total_rows'] = $totalRows;
        $config['per_page'] = 12;
        if (!isset($_GET[$config['query_string_segment']]) || $_GET[$config['query_string_segment']] < 1) {
            $_GET[$config['query_string_segment']] = 1;
        }
        $this->pagination->initialize($config);

        $limit = $config['per_page'];
        $offset = ($this->input->get($config['query_string_segment']) - 1) * $limit;

        return ['limit' => $limit, 'offset' => $offset];
    }

    public function index() {

    //call initialization method
        $config = $this->_initPagination("/", $this->Posts_model->get_num_rows());

        $data = $this->Static_model->get_static_data();
        $data['pages'] = $this->Pages_model->get_pages();
        $data['categories'] = $this->Categories_model->get_categories();  

        //use limit and offset returned by _initPaginator method
        $data['posts'] = $this->Posts_model->get_posts($config['limit'], $config['offset']);
        $this->load->view('partials/header', $data);
        $this->load->view('posts');
        $this->load->view('partials/footer');
    }

    public function search() {
    // Force validation since the form's method is GET
        $this->form_validation->set_data($this->input->get());
        $this->form_validation->set_rules('search', 'Search term', 'required|trim|min_length[3]',array('min_length' => 'The Search term must be at least 3 characters long.'));
        $this->form_validation->set_error_delimiters('<p class = "error search-error">', '</p>
            ');
        // If search fails
        if ($this->form_validation->run() === FALSE) {
            return $this->index();
        } else {
            $expression = $this->input->get('search');
            $posts_count = $this->Posts_model->search_count($expression);
            $query_string_segment = 'page';
            $config = $this->_initPagination("/posts/search", $posts_count, $query_string_segment);
            $data = $this->Static_model->get_static_data();
            $data['pages'] = $this->Pages_model->get_pages();
            $data['categories'] = $this->Categories_model->get_categories();
      //use limit and offset returned by _initPaginator method
            $data['posts'] = $this->Posts_model->search($expression, $config['limit'], $config['offset']);
            $data['expression'] = $expression;
            $data['posts_count'] = $posts_count;
            $this->load->view('partials/header', $data);
            $this->load->view('search');
            $this->load->view('partials/footer');
        }
    } 

    public function byauthor($authorid){
        $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->get_posts_by_author($authorid); 
        $data['posts_count'] = $this->Posts_model->posts_by_author_count($authorid); 
        $data['posts_author'] = $this->Posts_model->posts_author($authorid);

        $this->load->view('partials/header', $data);
        $this->load->view('posts_by_author');
        $this->load->view('partials/footer');
    }

    public function post($slug) {
        $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($slug);

        if ($data['categories']) {
            foreach ($data['categories'] as &$category) {
                $category->posts_count = $this->Posts_model->count_posts_in_category($category->id);
            }
        }

        if (!empty($data['post'])) {
            // Overwrite the default tagline with the post title
            $data['tagline'] = $data['post']->title;

            // Get post comments
            $post_id = $data['post']->id;
            $data['comments'] = $this->Comments_model->get_comments($post_id);

            $this->load->view('partials/header', $data);
            $this->load->view('post');
        } else {
            $data['tagline'] = "Page not found";
            $this->load->view('partials/header', $data);
            $this->load->view('404');
        }
        $this->load->view('partials/footer');
    }

    public function create() {

        // Only logged in users can create 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['tagline'] = "Add New Post";
        $data['categories'] = $this->Categories_model->get_categories();
        $data['posts'] = $this->Posts_model->sidebar_posts($limit=5, $offset=0);

        if ($data['categories']) {
            foreach ($data['categories'] as &$category) {
                $category->posts_count = $this->Posts_model->count_posts_in_category($category->id);
            }
        }

        $this->form_validation->set_rules('title', 'Title', 'required');
        $this->form_validation->set_rules('desc', 'Short description', 'required');
        $this->form_validation->set_rules('body', 'Body', 'required');
        $this->form_validation->set_error_delimiters('<p class="error-message">', '</p>');

        if($this->form_validation->run() === FALSE){
            $this->load->view('partials/header', $data);
            $this->load->view('create-post');
            $this->load->view('partials/footer');
        } else {
            // Create slug (from title)
            $slug = url_title($this->input->post('title'), 'dash', TRUE);
            $slugcount = $this->Posts_model->slug_count($slug);
            if ($slugcount > 0) {
                $slug = $slug."-".$slugcount;
            }

            // 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 = 'default.jpg';
            } else {
                $data = array('upload_data' => $this->upload->data());
                $post_image = $_FILES['userfile']['name'];
            }

            $this->Posts_model->create_post($post_image, $slug);
            $this->session->set_flashdata('post_created', 'Your post has been created');
            redirect('/');
        }
    }

    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 ( isset($_FILES['userfile']['name']) && $_FILES['userfile']['name'] != null ) 
        {
            // Use name field in do_upload method
            if (!$this->upload->do_upload('userfile')) {
                $errors = array('error' => $this->upload->display_errors());

            } else {
                $data = $this->upload->data();
                $post_image = $data[ 'raw_name'].$data[ 'file_ext'];
            }
        }
        else {
            $post_image = $this->input->post('postimage');
        }


        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);
        }
    }

    public function delete($slug) {
        // Only logged in users can delete posts
        if (!$this->session->userdata('is_logged_in')) {
            redirect('login');
        }

        $data['post'] = $this->Posts_model->get_post($slug);
        if ($this->session->userdata('user_id') == $data['post']->author_id) 
      {
            $this->Posts_model->delete_post($slug);
            $this->session->set_flashdata('post_deleted', 'The post has been deleted');
            redirect('/');
        } else {
            /* If the current user is not the author
            of the post do not alow delete */
            redirect('/' . $slug);
        }
      }    
    }

Please help me with useful feedback and suggestions.


Get this bounty!!!

#StackBounty: #php #codeigniter Values from textbox array not updating

Bounty: 50

Im new in this forum and i’m having a hard time updating selected value from checkbox coming from the textbox value.

Scenraio:

I want to update selected items, For example I want to update Item-2 and the textbox from item recieve will be enable, I will enter a number for example 1 and the textbox from total receive will automatically sum using ajax.

The problem is after submiting the value from total recieve the records that was updating is blank, but when I try to check and print_r the value is there.

And one more thing if all checkbox are all checked and enter a number for each item recieve, the value that it only get is the last value and will be updated will all selected checkbox.

Note:
Checkbox is an array
Textbox from total recieve is an array

Can you guys please help me?

Here’s my UI:

enter image description here

Controller:

public function recitem_insert(){

$this->load->model('dbquery');    

$check = $this->input->post('check');    
$total_rec = $_POST['total_rec'];


if(isset($check)){ //Check if check is checked    

  for($i=0;$i<sizeof($check);$i++){
    for($j=0;$j<sizeof($total_rec);$j++){    

    $updateData = array('rec_qty' => $total_rec[$j] );                                                        
    $this->dbquery->modUpdatedynamicval('tblstock', 'id', $updateData, $check[$i]);

       }        
   }//end for loop    

    echo "
        alert('Successfully Added!');
        window.close();
        ";        

}else{ //End If
      echo 'Please select a checkbox';
    }

}

View:

<form method="post" action="<?php echo base_url() ?>user/recitem_insert">

System ID:

<!-- /.box-header -->
db->query("SELECT * FROM tblstock where process_id = '$process_id'"); foreach ($query->result() as $row){ ?> rec_qty; ?>">
Action Item Code Item Description Required QTY Order Last QTY Recieve Item Recieve Total Recieve
id; ?>" onclick="valueChanged()"> item_code; ?> description; ?> qty_order; ?> rec_qty; ?>
<!-- /.box-body --> </div> </form>

Model:

public function modUpdatedynamicval($table, $column, $data, $equal_to){

$this->db->where($column, $equal_to);
$this->db->update($table, $data);         

}

Any help will be gladly appreciate.

Thank you..

EDIT:

Lets assume,
I’ve input 1 in item_receive textbox one and the total recieve will be 10,
2 in item_receive textbox two and the total recieve will be 11,
3 in item_receive textbox three and the total recieve will be 12,

enter image description here

CODE:

$check = $this->input->post('check');   
$total_rec = $_POST['total_rec'];

echo 'Check Value';
print_r($check);

echo '<br><br>';

echo 'Total Recieve';
print_r($total_rec);

OUTPUT:

Check ValueArray ( [0] => 1 [1] => 2 [2] => 3 ) 

Total RecieveArray ( [0] => 10 [1] => 11 [2] => 12 )

But If I only inout the second textbox here’s the output:

Check ValueArray ( [0] => 2 ) 

Total RecieveArray ( [0] => [1] => 11 [2] => )


Get this bounty!!!