I am trying to get a user to enter their details and then store those in a database using codeigniter. When I try and add an entry I get taken to the page where it says success but it does not add anything to the database.
Here are the model and the controller files -
signup.php - This is the controller
<?php
class Signup extends CI_Controller{
function index(){
$this->load->view('signup_form');
}
function insert_member(){
//load model
$this->load->model('insert_member_model');
if($q = $this->insert_member_model->new_member()){
$data['content'] = 'success';
$this->load->view('trial', $data);
}
}
}
insert_member_model.php - This is the model
class Insert_member_model extends CI_Model{
function new_member(){
$new_member_data = array(
'first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post('last_name'),
'username' => 'NULL',
'password' =>$this->input->post('password'),
'email_address' => $this->input->post('email_address')
);
$insert = $this->db->where('membership', $new_member_data);
return $insert;
}
}
Can anyone please help.
Thanks in advance
In insert_member_model.php Replace:
$this->db->where('membership', $new_member_data);
with:
$this->db->insert('membership', $new_member_data);
To insert the data into the database.
Related
I am having trouble with updating the content of two tables. The tables are about users, first table is used for login purposes, so it contains username, email and pass, while the second one is used for user details. Both are connected with the ID of the user row. I am having trouble updating these contents. Here is my code, I am new to CI, so basically don't have a clue what goes wrong.
controller:
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Student extends CI_Controller {
public function index()
{
$this->load->model('student_model');
$data['all_students'] = $this->student_model->get_student_list();
$this->load->view('admin_panel', $data);
}
public function view_student()
{
$this->load->model('student_model');
$data['one_student'] = $this->student_model->get_one_student();
$this->load->view('view_student', $data);
}
public function edit_student()
{
$this->load->model('student_model');
$data['one_student'] = $this->student_model->get_one_student();
$this->load->view('edit_student', $data);
}
public function update_student()
{
$this->load->model('student_model');
$data['update_student'] = $this->student_model->update_student();
$this->load->view('admin_panel', $data);
}
}
View
<?php $this->load->view('worker_templates/wheader');
$this->output->enable_profiler(TRUE);
$this->load->helper('form');
echo "<br/><br/><br/><br/><br/>";
echo form_open('student/update_student');
foreach ($one_student as $key => $value)
{
echo "<div class='col-md-6'>";
echo form_label('Name ', 'worker_name');
echo form_input('Name', $value['worker_name']);
echo form_label('Role ', 'role');
echo form_input('Role', $value['role']);
echo form_label('Email ', 'worker_email');
echo form_input('Email', $value['worker_email']);
echo "<br/><br/>";
echo form_label('Phone ', 'phone');
echo form_input('Phone', $value['phone']);
...
This is very long, So I'm not copying it all to bore you.
Model:
public function get_one_student() //used to show a student, also to display data of one student for update
{
$this->db->select('*');
$this->db->from('workers');
$this->db->join('worker_details', 'worker_details.student_id = workers.worker_id');
$this->db->where('worker_id', $_GET['id']);
$q = $this->db->get();
return $q->result_array();
}
public function update_student()
{
$data = array(
'worker_name' => $this->input->post('worker_name'),
'worker_email' => $this->input->post('worker_email'),
'role' => $this->input->post('role'));
$this->db->update('workers', $data); //first table
$data2 = array(
'phone' => $this->input->post('phone'),
'date_of_birth' => $this->input->post('date_of_birth'),
'sex' => $this->input->post('sex'),
'university' => $this->input->post('university'),
'speciality' => $this->input->post('speciality'),
... //again, very long, not including it all
);
$this->db->update('worker_details', $data2);//second table
}
You need to correct your update_student() function in model. please post worker_id in hidden from your html form and correct function as below.
public function update_student()
{
$data = array(
'worker_name' => $this->input->post('worker_name'),
'worker_email' => $this->input->post('worker_email'),
'role' => $this->input->post('role'));
$this->db->where('worker_id', $this->input->post('worker_id'));
$this->db->update('workers', $data); //first table
$data2 = array(
'phone' => $this->input->post('phone'),
'date_of_birth' => $this->input->post('date_of_birth'),
'sex' => $this->input->post('sex'),
'university' => $this->input->post('university'),
'speciality' => $this->input->post('speciality'),
... //again, very long, not including it all
);
$this->db->where('worker_id', $this->input->post('worker_id'));
$this->db->update('worker_details', $data2);//second table
}
Code-igniter Session is not storing data, it only saves the Email which we are entering in input box in login-form. I set this $config['sess_use_database'] = TRUE; and created a ci_sessions table also in DB but no sake. I tried this on both versions on code-igniters(2 & 3) Please help me to sort out this problem. Thank you. This is my code. First one is controller and the second one is model.
public function validate_credentials()
{
$this->load->model('passenger_login_model');
$query = $this->passenger_login_model->validate();
if($query)
{
$data = array(
'Email' => $this->input->post('Email'),
'is_logged_in' => true,
'P_ID' => $query->P_ID,
'CNIC' => $query->CNIC
);
$this->session->set_userdata($data);
echo $this->session->userdata('Email');
echo $this->session->userdata('P_ID');
//redirect('front');
}
else
{
echo "<script>alert('Incorrect Email or Password!');</script>";
$this->index();
}
}
and as output, it only shows me the user#user.com not P_ID
and this is model
class Passenger_Login_model extends CI_Model
{
/*`passenger`(`P_ID`, `Name`, `Image`, `CNIC`, `Passport_No`, `Gender`, `Email`,
`Password`, `Phone_No`, `Mob_No`, `Address_1`, `Address_2`, `Date` */
function validate()
{
$data=array(
'Email' =>$this->input->post('Email'),
'Password' =>$this->input->post('Password')
);
$rec=$this->db->get_where('passenger', $data)->result();
$c = count($rec);
if($c>0)
{
return true;
}
else
{
return false;
}
}
function is_logged_in()
{
$this->load->library('session');
$is_logged_in = $this->session->userdata('is_logged_in');
if(!isset($is_logged_in) || $is_logged_in != true)
{
echo 'You don\'t have permission to access this page.'.anchor('login',"Login");
die();
}
}}
You should return the data fetch from your model query, use fetch function to do that, for more reference click, So your model validate function should be
function validate()
{
$data=array(
'Email' =>$this->input->post('Email'),
'Password' =>$this->input->post('Password')
);
$rec=$this->db->get_where('passenger', $data);
return $rec->result_array(); // returns data as array // might help you
}
return $res->result_array(); will return multipdimentional array of data from db, to know more about result_array() check this
Session issue is from your controller function the result is array now.
public function validate_credentials()
{
$this->load->model('passenger_login_model');
$result_data = $this->passenger_login_model->validate();
// result data is array now
if(is_array($result_data) && count($result_data) > 0)
{
// var_dump($result_data); // check this var_dump you will get multidimensional array
$data = array(
'Email' => $this->input->post('Email'),
'is_logged_in' => true,
'P_ID' => $result_data[0]['P_ID'],
'CNIC' => $result_data[0]['CNIC']
);
$this->session->set_userdata($data);
echo $this->session->userdata('Email');
echo $this->session->userdata('P_ID');
//redirect('front');
}
else
{
echo "<script>alert('Incorrect Email or Password!');</script>";
$this->index();
}
}
Hope this help, Happy coding.
My problem solved, i just updated the model to this...
function validate()
{
$data=array(
'Email' =>$this->input->post('Email'),
'Password' =>$this->input->post('Password')
);
$query = $this->db->get('passenger');
if ($query->num_rows())
{
return $query->row();
}
}
Hello everybody i need help on codeigniter roles or permision. i have one user role (the admin) :
Table users ine the database :
id int(11)
email varchar(100)
password varchar(128)
name varchar(100)
in my admin panel i have (page.php controller)=page management, page order, (agent.php controller) = add,edit,delete... , (gyms) = add,edit,delete... ,(article.php controller)
and i have 21 sections, for each section i have more than one treatment, what i want is to assign to each section an admin than can edit and view only his section. so i will have 21 section_admin and one (or more) global_admin than can manage everything
i add an other field in users table named type :
type varchar(50)
it will have two values section_admin or global_admin. I searched but i found no tutorial that shows me how do that.
i don't know how to integrate roles management in my system. Can someone help me?
The controler : user.php
class User extends Admin_Controller
{
public function __construct ()
{
parent::__construct();
}
public function index ()
{
// Fetch all users
$this->data['users'] = $this->user_m->get();
// Load view
$this->data['subview'] = 'admin/user/index';
$this->load->view('admin/_layout_main', $this->data);
}
public function edit ($id = NULL)
{
// Fetch a user or set a new one
if ($id) {
$this->data['user'] = $this->user_m->get($id);
count($this->data['user']) || $this->data['errors'][] = 'User could not be found';
}
else {
$this->data['user'] = $this->user_m->get_new();
}
// Set up the form
$rules = $this->user_m->rules_admin;
$id || $rules['password']['rules'] .= '|required';
$this->form_validation->set_rules($rules);
// Process the form
if ($this->form_validation->run() == TRUE) {
$data = $this->user_m->array_from_post(array('name', 'email', 'password'));
$data['password'] = $this->user_m->hash($data['password']);
$this->user_m->save($data, $id);
redirect('admin/user');
}
// Load the view
$this->data['subview'] = 'admin/user/edit';
$this->load->view('admin/_layout_main', $this->data);
}
public function delete ($id)
{
$this->user_m->delete($id);
redirect('admin/user');
}
public function login ()
{
// Redirect a user if he's already logged in
$dashboard = 'admin/dashboard';
$this->user_m->loggedin() == FALSE || redirect($dashboard);
// Set form
$rules = $this->user_m->rules;
$this->form_validation->set_rules($rules);
// Process form
if ($this->form_validation->run() == TRUE) {
// We can login and redirect
if ($this->user_m->login() == TRUE) {
redirect($dashboard);
}
else {
$this->session->set_flashdata('error', 'That email/password combination does not exist');
redirect('admin/user/login', 'refresh');
}
}
// Load view
$this->data['subview'] = 'admin/user/login';
$this->load->view('admin/_layout_modal', $this->data);
}
public function logout ()
{
$this->user_m->logout();
redirect('admin/user/login');
}
public function _unique_email ($str)
{
// Do NOT validate if email already exists
// UNLESS it's the email for the current user
$id = $this->uri->segment(4);
$this->db->where('email', $this->input->post('email'));
!$id || $this->db->where('id !=', $id);
$user = $this->user_m->get();
if (count($user)) {
$this->form_validation->set_message('_unique_email', '%s should be unique');
return FALSE;
}
return TRUE;
}
}
The model user_m.php :
protected $_table_name = 'users';
protected $_order_by = 'name';
public $rules = array(
'email' => array(
'field' => 'email',
'label' => 'Email',
'rules' => 'trim|required|valid_email|xss_clean'
),
'password' => array(
'field' => 'password',
'label' => 'Password',
'rules' => 'trim|required'
)
);
public $rules_admin = array(
'name' => array(
'field' => 'name',
'label' => 'Name',
'rules' => 'trim|required|xss_clean'
),
'email' => array(
'field' => 'email',
'label' => 'Email',
'rules' => 'trim|required|valid_email|callback__unique_email|xss_clean'
),
'password' => array(
'field' => 'password',
'label' => 'Password',
'rules' => 'trim|matches[password_confirm]'
),
'password_confirm' => array(
'field' => 'password_confirm',
'label' => 'Confirm password',
'rules' => 'trim|matches[password]'
),
);
function __construct ()
{
parent::__construct();
}
public function login ()
{
$user = $this->get_by(array(
'email' => $this->input->post('email'),
'password' => $this->hash($this->input->post('password')),
), TRUE);
if (count($user)) {
// Log in user
$data = array(
'name' => $user->name,
'email' => $user->email,
'id' => $user->id,
'loggedin' => TRUE,
);
$this->session->set_userdata($data);
}
}
public function logout ()
{
$this->session->sess_destroy();
}
public function loggedin ()
{
return (bool) $this->session->userdata('loggedin');
}
public function get_new(){
$user = new stdClass();
$user->name = '';
$user->email = '';
$user->password = '';
return $user;
}
public function hash ($string)
{
return hash('sha512', $string . config_item('encryption_key'));
}
}
There's too many ways how you can incorporate permission system in your project and it all depends what you need. I will give you a basic idea for your case how I would do it IF I understood your question right:
Yes, you can add another field to user table and call it role
To your section table add a user_id field. This is how you connect user with section.
Once user logs in, veryfy if that user is section_user and if yes you need to pull the right section based on that user_id from db.
If not, it means its a global_admin and then display all sections.
I'm not sure if I understood your question right tho.
Let me know.
Save yourself the trouble and use this: Flexi-Auth. You'll have roles and permissions for all the admin types you want for example.
I'm not sure exactly what you're trying to achieve, but I'll explain roughly what I would do:
1) Define a URL scheme
For example if you had a website for car enthusiasts, each brand might be its own section:
somesite.com/section/honda
somesite.com/section/ford
somesite.com/section/toyota
Those URL slugs (honda, ford, toyota etc) effectively become the identifiers for the section you're trying to access. Each one is unique.
You would then want to make sure that each slug after /section/ is a parameter rather than a function call. You can do this by going into /application/config/routes.php and defining a route like this:
$route['section/(:any)'] = section_controller/$1;
// $1 is the placeholder variable for the (:any) regex. So anything that comes after /section will be used as a parameter in the index() function of the section_controller class.
2. Create a new database called 'section', and a corresponding model
For now just give it two fields: *section_id*, and *section_name*. This will store each unique section. The code for the model would be something like this:
class Section extends CI_Model
{
public $section_name;
public $section_id;
public function loadByName($section_name)
{
$query = $this->db->select('section_id', 'section_name')
->from('section')
->where('section_name', $section_name);
$row = $query->row();
$this->section_name = $row->section_name;
$this->section_id = $row->section_id;
return $row;
}
public function loadById($section_id)
{
$query = $this->db->select('section_id', 'section_name')
->from('section')
->where('section_id', $section_id);
$row = $query->row();
$this->section_name = $row->section_name;
$this->section_id = $row->section_id;
return $row;
}
}
3. In the user table, create an additional field called *section_id*
This will be the reference to the ID of the section which they are an admin of. For example if the Toyota section_id is 381, then use 381 as the number in the section_id field in the user table.
4. When the page is requested, look up the section_id based on the slug name.
In your controller file, you should then load the section model somewhere in the index() method like so:
class Section_controller extends CI_Controller
{
public function index($section_name)
{
// I will assume you've already loaded your logged in User somewhere
$this->load->model('Section');
$this->Section->loadByName($section_name);
if ($this->User->section_id == $this->Section->section_id)
{
// Render the page with appropriate permissions
}
else
{
// Throw an error
}
}
}
I won't get into any more specifics of doing all of that; you'll have to read the Codeigniter documentation for a grasp on how to handle routes, controllers, DB queries etc.
if you have only 2 roles then it can achieve easily. you know the user is admin or not if user >is admin then it activate all the section where admin has acess. if user is then he won,t able >to gain access.
if you are comfortalbe to use tankauth authentication library if you have enough time to do task then go to tankauth.
you can also use bonfire(HMVC) for user authentication.
I am currently trying to add data to the database using codeigniter. I have already set up a registration page using the active method and attempted to use the same method for the add news form but was unsuccessful.
When I click submit it is saying page cannot be found and the url shows the controller function name. This is the same when i purposely leave any fields blank. I have checked my database and no records have been added and no php log errors.
Here is my snippets of code:
View:
<?php echo form_open('add/add_article'); ?>
<?php echo form_input('title', set_value('title', 'Title')); ?><br />
<?php echo form_textarea('content', set_value('content', 'Content')); ?><br />
<?php echo form_input('author', set_value('author', 'Author')); ?>
<?php echo form_submit('submit', 'Add Article'); ?>
<?php echo validation_errors('<p class="error">' );?>
<?php echo form_close(); ?>
Controller:
class Add extends CI_Controller {
public function __construct() {
parent::__construct();
}
public function index() {
$this->load->view('admin/add');
}
public function add_article() {
$this->load->library('form_validation');
$this->form_validation->set_rules('title', 'Title', 'trim|required');
$this->form_validation->set_rules('content', 'Content', 'trim|required');
$this->form_validation->set_rules('author', 'Author', 'trim|required');
if($this->form_validation->run() == FALSE) {
$this->index();
}else{
$this->load->model('news_model');
if($query = $this->news_model->addArticle()) {
$this->load->view('news');
}else {
$this->load->view('news');
}
}
}
}
Model:
public function __construct() {
parent::__construct();
}
function addArticle() {
$data =array(
'title' => $this->input->post('title'),
'content' => $this->input->post('content'),
'author' => $this->input->post('author'),
'username' => $this->input->post('username'));
$insert = $this->db->insert('news', $data);
return $insert;
}
}
If it's the server that's throwing the page not found it's almost certainly a URL issue as opposed to a CI/PHP issue.
Is your base url defined properly in the config file? Is your .htaccess configured properly (an old configuration could be routing /add requests away from CI)?
Try adding the following action to the Add controller, and navigating to it directly at http://[base]/add/thetest
public function thetest() {
echo 'Controller accessed';
die;
}
If it still says page not found it's not your code, it's your config (either server config or CI).
Instead of insert use update in your model like:
$insert = $this->db->update('news', $data);
return $insert;
And I think that this part of your code in controller is wrong too (wrong if statement and no data send to model):
if($query = $this->news_model->addArticle()) {
$this->load->view('news');
}else {
$this->load->view('news');
}
try this:
$data =array(
'title' => $this->input->post('title'),
'content' => $this->input->post('content'),
'author' => $this->input->post('author'),
'username' => $this->input->post('username')
);
$query = $this->news_model->addArticle($data);
if($query)
{
// query ok
$this->load->view('news');
}
else {
// no query
$this->load->view('news');
}
in my Zend Framework project, I use a Service Layer, however I don't really know where to handle errors.
For example, let's say I've a UserService::updateUser($data);
What if I've:
$data = array(
'userId' => 2,
'firstName' => 'Jane',
'lastName' => 'Doe',
);
And user with id 2 doesn't exist?
Where and how would you handle such errors?
You can forward to a specific controller to handle all your business errors, like this :
if ($error=true)
return $this->_forward('standarderror', 'businesserror', 'default',
array('msgtitle' => $this->view->translate('item_not_found'),
'msg' => $this->view->translate('item_not_found_msg')));
and where your BusinesserrorController looks like :
class BusinesserrorController extends Zend_Controller_Action {
public function init() {
$this->_helper->viewRenderer->setNoRender();
}
public function standarderrorAction() {
$msgtitle = $this->_getParam('msgtitle');
$msg = $this->_getParam('msg');
$this->view->errortitle = $msgtitle;
$this->view->errormessage = $msg;
$this->view->nextstep = $this->view->translate('return_to_the_homepage');
$this->view->nextstepurl = "/";
echo $this->render('error/businesserror', null, true);
}
}
you can parametrize the forwarded url as well ;)