Controller not acting correctly - php

I'm new to code igniter but I've been watching many youtube videos and I'm starting to get the hang of the basics of it however after I do a test run on my registration form it goes to a white page with The requested URL /kowmanager/user/register was not found on this server. I'm not sure why. Any ideas?
Controller:
function User()
{
parent :: __construct();
$this->view_data['base_url'] = base_url();
$this->load->model('User_model');
}
function index()
{
$this->register();
}
function register()
{
$this->form_validation->set_rules('username', 'Username', 'trim|required|alpha_numeric|min_length[6]|xss_clean|strtolower|callback_usernameNotExists');
$this->form_validation->set_rules('password', 'Password', 'trim|required|alpha_numeric|min_length[6]|xss_clean');
$this->form_validation->set_rules('passwordConfirm', 'Confirm Password', 'trim|required|alpha_numeric|min_length[6]|xss_clean|matches[password]');
$this->form_validation->set_rules('email', 'Email', 'trim|required|min_length[6]|xss_clean|valid_email|callback_emailNotExists');
$this->form_validation->set_rules('firstName', 'First Name', 'trim|required|alpha_numeric|min_length[6]|xss_clean');
$this->form_validation->set_rules('lastName', 'Last Name', 'trim|required|alpha_numeric|min_length[6]|xss_clean');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('view_register', $this->view_data);
}
else
{
$username = $this->input->post('username');
$password = $this->input->post('password');
$email = $this->input->post('email');
$firstName = $this->input->post('firstName');
$lastName = $this->input->post('lastName');
$registrationKey = substr(md5(mt_rand()), 0, 5);
$this->User_model->registerUser($username, $password, $email, $firstName, $lastName, $registrationKey);
}
}
function usernameNotExists($username)
{
$this->form_validation->set_message('usernameNotExists', ' That %s already exists inside the database!');
if($this->User_model->checkExistsUsername($username))
{
return false;
}
else
{
return true;
}
}
function emailNotExists($username)
{
$this->form_validation->set_message('emailNotExists', ' That %s already exists inside the database!');
if($this->User_model->checkExistsEmail($email))
{
return false;
}
else
{
return true;
}
}
}
?>
View Page:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<title>KOW Manager Registration Form</title>
</head>
<body>
<?php
echo form_open($base_url . 'user/register');
$username = array ('name' => 'username', 'id' => 'username', 'value' => set_value('username'));
$password = array ('name' => 'password', 'id' => 'password', 'value' => '');
$passwordConfirm = array ('name' => 'passwordConfirm', 'id' => 'passwordConfirm', 'value' => '');
$email = array ('name' => 'email', 'id' => 'email', 'value' => set_value('email'));
$firstName = array ('name' => 'firstName', 'id' => 'firstName', 'value' => set_value('firstName'));
$lastName = array ('name' => 'lastName', 'id' => 'lastName', 'value' => set_value('lastName'));
?>
<?php echo form_fieldset('User Information') ?>
<dl>
<dt><label for="username">Username:</label></dt>
<dd><?php echo form_input($username); ?></dd>
</dl>
<dl>
<dt><label for="password">Password:</label></dt>
<dd><?php echo form_password($password); ?></dd>
</dl>
<dl>
<dt><label for="passwordConfirm">Confirm Password:</label></dt>
<dd><?php echo form_password($passwordConfirm); ?></dd>
</dl>
<dl>
<dt><label for="email">Email Address:</label></dt>
<dd><?php echo form_input($email); ?></dd>
</dl>
<dl>
<dt><label for="firstName">First Name:</label></dt>
<dd><?php echo form_input($firstName); ?></dd>
</dl>
<dl>
<dt><label for="lastName">Last Name:</label></dt>
<dd><?php echo form_input($lastName); ?></dd>
</dl>
<?php echo form_fieldset_close() ?>
<?php echo validation_errors() ?>
<dl class="submit">
<?php echo form_submit(array('name' => 'register'), 'Register'); ?>
</dl>
<?php echo form_close(); ?>
</body>
</html>
Edit:
Here's my new code which is still doing the same thing.
<?php
class User extends CI_Controller {
function User()
{
parent :: __construct();
$this->view_data['base_url'] = base_url();
$this->load->model('User_model');
}
function index()
{
$this->register();
}
function register()
{
$this->form_validation->set_rules('username', 'Username', 'trim|required|alpha_numeric|min_length[6]|xss_clean|strtolower|callback_usernameNotExists');
$this->form_validation->set_rules('password', 'Password', 'trim|required|alpha_numeric|min_length[6]|xss_clean');
$this->form_validation->set_rules('passwordConfirm', 'Confirm Password', 'trim|required|alpha_numeric|min_length[6]|xss_clean|matches[password]');
$this->form_validation->set_rules('email', 'Email', 'trim|required|min_length[6]|xss_clean|valid_email|callback_emailNotExists');
$this->form_validation->set_rules('firstName', 'First Name', 'trim|required|alpha_numeric|min_length[6]|xss_clean');
$this->form_validation->set_rules('lastName', 'Last Name', 'trim|required|alpha_numeric|min_length[6]|xss_clean');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('view_register', $this->view_data);
}
else
{
$username = $this->input->post('username');
$password = $this->input->post('password');
$email = $this->input->post('email');
$firstName = $this->input->post('firstName');
$lastName = $this->input->post('lastName');
$registrationKey = substr(md5(mt_rand()), 0, 5);
$this->User_model->registerUser($username, $password, $email, $firstName, $lastName, $registrationKey);
$this->load->library('email');
$this->email->from('kowmanagement#kansasoutlawwrestling.com', 'KOW Management');
$this->email->to($email);
$this->email->subject('KOW Manager Account Registration');
$this->email->message('Hello '.$firstName.' '.$lastName.' Welcome to our website!<br /><br />You, or someone using your email address, has completed registration at '.myDomainName().'. You can complete registration by clicking the following link:<br /><br />' . anchor('http://www.'.myDomainName().'/manager/verify.php?userID='.$userID.'&verifyHash='.$verifyHash.'", http://www.'.myDomainName().'/manager/verify.php?userID='.$userID.'&verifyHash='.$verifyHash.''));
$this->email->send();
}
}
function registerConfirm()
{
$registrationKey = $this->uri->segment(3);
if ($registrationKey == '')
{
echo 'No registration key found in URL';
exist();
}
$registrationConfirmed = $this->User_model->confirmRegistration($registrationKey);
if ($registrationConfirmed)
{
echo 'You have successfully registered!';
}
else
{
echo 'You have failed to register!';
}
}
function usernameNotExists($username)
{
$this->form_validation->set_message('usernameNotExists', ' That %s already exists inside the database!');
if($this->User_model->checkExistsUsername($username))
{
return false;
}
else
{
return true;
}
}
function emailNotExists($username)
{
$this->form_validation->set_message('emailNotExists', ' That %s already exists inside the database!');
if($this->User_model->checkExistsEmail($email))
{
return false;
}
else
{
return true;
}
}
function myDomainName()
{
$my_domain = $_SERVER['HTTP_HOST'];
$my_domain = str_replace('www.', '', $my_domain);
return $my_domain;
}
}
?>
Any other ideas?

CodeIgniter routes by default are structured like this.
http://example.com/index.php/Controller/Function
If you don't have 'index.php' in your code it isn't going to be routed correctly unless you have a mod_rewrite rule setup in Apache.
try setting up your url like this
http://domain/index.php/user/register
and see what happens.
Check this out:
http://codeigniter.com/wiki/mod_rewrite/

Bear in mind that what you are doing is this:
mysite.com/kowmanager/user/register
or
mysite.com/index.php/kowmanager/user/register
in either case
1) you are using the knownmanager Directory
2) you are using the controller user
3) you are calling the method 'register'
You can check the following things:
It looks like you are using your user method as a constructor if you are using CI 2 use
function __constructor() {
parent::__constructor();
}
as your constructor.
also you are not calling the view in this controller, are you using a different controller to call the view? I would create a new method called registration_form and call the view from there:
$data['data'] = array();
$this->load->view('view_name', $data);
In this case what you would do is use the following url
mysite.com/kowmanager/index.php/user/registration_form/
Then when the form is submitted it will call the validation method.
I'm not sure if you are loading form_validation before using it
$this->load->library('form_validation');
Good Luck!

Try setting you base_url. If you're working locally and using MAMP or XAMP, it would be something like this:
$config['base_url'] = 'http://localhost/kowmanager';

Related

Codeigniter foreach loop error

I am getting a foreach loop error in codeigniter, it was working fine, but once I moved the project to a new hosting I get an error for the loop. Both servers are using PHP 7.2
Here is the first error:
Message: array_slice() expects parameter 1 to be array, null given
And here is the second error:
Message: Invalid argument supplied for foreach()
The backtrace says the error is in the controller, I have checked many times and tried many methods but still the same.
Using is_array PHP function wont help, as it only hide the error messages, but the functions wont work as before.
Controller:
public function login(){
$data['title'] = 'Sign In';
$this->form_validation->set_rules('email', 'Email', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
if($this->form_validation->run() === FALSE){
$this->load->view('templates/header', $data);
$this->load->view('users/login', $data);
$this->load->view('templates/footer');
} else {
// Get username
$username = $this->input->post('email');
// Get and encrypt the password
$password = $this->input->post('password');
// Login user
$user_id = $this->user_model->login($username, $password);
if($user_id){
// Create session
$user_data = array(
'id' => $user_id,
'email' => $username,
'logged_in' => true
);
$this->session->set_userdata($user_data);
// Set message
$this->session->set_flashdata('user_loggedin', 'Login Success');
redirect('users/account');
} else {
// Set message
$this->session->set_flashdata('login_failed', 'Login Faild');
redirect('users/login');
}
}
}
public function account($id = NULL){
if(!$this->session->userdata('logged_in')){
redirect('users/login');
}
$data['users'] = $this->user_model->get_users($this->session->userdata('id'));
$data['title'] = 'Account';
$this->load->view('templates/user_header', $data);
$this->load->view('users/account', $data);
$this->load->view('templates/user_footer');
}
Loop code:
<?php foreach (array_slice($users, 0, 1) as $user): ?>
<div><p><?php echo $user['first_name'] ?></p></div>
<?php endforeach; ?>
Model:
public function get_users($id){
$this->db->join('user_details', 'user_details.user_details_id = users.id');
$this->db->join('user_orders', 'user_orders.user_id = users.id');
$query = $this->db->get_where('users', array('id' => $id));
return $query->row_array();
}
Rewrite the below code:
<?php foreach (array_slice($users, 0, 1) as $user): ?>
<div><p><?php echo $user['first_name'] ?></p></div>
<?php endforeach; ?>
as:
<div><p><?php echo $users['first_name'] ?></p></div>
Because:
public function get_users($id){
$this->db->join('user_details', 'user_details.user_details_id = users.id');
$this->db->join('user_orders', 'user_orders.user_id = users.id');
$query = $this->db->get_where('users', array('id' => $id));
return $query->row_array();
}
This code will not return an multi-dimension array... you have used row_array() which will be a single array.

Forgot password function not working in CodeIgniter

Good day! I'm trying to make a forgot password function in the CodeIgniter framework but I'm getting 2 errors when i try to send the e-mail.
Some database info (I'm using phpMyAdmin):
Db name: kadokado
Db table name: users
Db email column: email
Db password column: wachtwoord
My controller file (Auth.php) :
<?php
class Auth extends CI_Controller{
public function forgot()
{
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
if($this->form_validation->run() == FALSE) {
$this->load->view('templates/header');
$this->load->view('forgot');
$this->load->view('templates/footer');
}else{
$email = $this->input->post('email');
$clean = $this->security->xss_clean($email);
$userInfo = $this->user_model->getUserInfoByEmail($clean);
if(!$userInfo){
$this->session->set_flashdata('flash_message', 'We hebben dit email adres niet kunnen vinden');
redirect(site_url().'auth/login');
}
if($userInfo->status != $this->status[1]){ //if status is not approved
$this->session->set_flashdata('flash_message', 'Your account is not in approved status');
redirect(site_url().'auth/login');
}
//build token
$token = $this->user_model->insertToken($userInfo->id);
$qstring = $this->base64url_encode($token);
$url = site_url() . 'auth/reset_password/token/' . $qstring;
$link = '' . $url . '';
$message = '';
$message .= '<strong>A password reset has been requested for this email account</strong><br>';
$message .= '<strong>Please click:</strong> ' . $link;
echo $message; //send this through mail
exit;
}
}
public function reset_password()
{
$token = $this->base64url_decode($this->uri->segment(4));
$cleanToken = $this->security->xss_clean($token);
$user_info = $this->user_model->isTokenValid($cleanToken); //either false or array();
if(!$user_info){
$this->session->set_flashdata('flash_message', 'Token is invalid or expired');
redirect(site_url().'auth/login');
}
$data = array(
'voornaam'=> $user_info->voornaam,
'email'=>$user_info->email,
'token'=>base64_encode($token)
);
$this->form_validation->set_rules('wachtwoord', 'Wachtwoord', 'required|min_length[5]');
$this->form_validation->set_rules('passconf', 'Password Confirmation', 'required|matches[wachtwoord]');
if ($this->form_validation->run() == FALSE) {
$this->load->view('templates/header');
$this->load->view('reset_password', $data);
$this->load->view('templates/footer');
}else{
$this->load->library('wachtwoord');
$post = $this->input->post(NULL, TRUE);
$cleanPost = $this->security->xss_clean($post);
$hashed = $this->password->create_hash($cleanPost['wachtwoord']);
$cleanPost['wachtwoord'] = $hashed;
$cleanPost['user_id'] = $user_info->id;
unset($cleanPost['passconf']);
if(!$this->user_model->updatePassword($cleanPost)){
$this->session->set_flashdata('flash_message', 'Er is iets foutgegaan');
}else{
$this->session->set_flashdata('flash_message', 'Uw wachtwoord is geupdate, u kunt nu inloggen');
}
redirect(site_url().'auth/login');
}
}
}
My model file (User_Model.php) :
<?php
class user_model extends CI_model {
public function getUserInfoByEmail($email)
{
$q = $this->db->get_where('users', array('email' => $email), 1);
if($this->db->affected_rows() > 0){
$row = $q->row();
return $row;
}else{
error_log('no user found getUserInfo('.$email.')');
return false;
}
}
public function getUserInfo($user_id)
{
$q = $this->db->get_where('users', array('user_id' => $user_id), 1);
if($this->db->affected_rows() > 0){
$row = $q->row();
return $row;
}else{
error_log('no user found getUserInfo('.$user_id.')');
return false;
}
}
public function insertToken($user_id)
{
$token = substr(sha1(rand()), 0, 30);
$date = date('Y-m-d');
$string = array(
'token'=> $token,
'user_id'=>$user_id,
'created'=>$date
);
$query = $this->db->insert_string('tokens',$string);
$this->db->query($query);
return $token . $user_id;
}
public function isTokenValid($token)
{
$tkn = substr($token,0,30);
$uid = substr($token,30);
$q = $this->db->get_where('tokens', array(
'tokens.token' => $tkn,
'tokens.user_id' => $uid), 1);
if($this->db->affected_rows() > 0){
$row = $q->row();
$created = $row->created;
$createdTS = strtotime($created);
$today = date('Y-m-d');
$todayTS = strtotime($today);
if($createdTS != $todayTS){
return false;
}
$user_info = $this->getUserInfo($row->user_id);
return $user_info;
}else{
return false;
}
}
}
?>
My view file (reset_password.php) :
<div class="col-lg-4 col-lg-offset-4">
<h2>Reset your password</h2>
<h5>Hello <span><?php echo $firstName; ?></span>, Voer uw wachtwoord 2x in aub</h5>
<?php
$fattr = array('class' => 'form-signin');
echo form_open(site_url().'auth/reset_password/token/'.$token, $fattr); ?>
<div class="form-group">
<?php echo form_password(array('name'=>'wachtwoord', 'id'=> 'wachtwoord', 'placeholder'=>'Wachtwoord', 'class'=>'form-control', 'value' => set_value('wachtwoord'))); ?>
<?php echo form_error('password') ?>
</div>
<div class="form-group">
<?php echo form_password(array('name'=>'passconf', 'id'=> 'passconf', 'placeholder'=>'Confirm Password', 'class'=>'form-control', 'value'=> set_value('passconf'))); ?>
<?php echo form_error('passconf') ?>
</div>
<?php echo form_hidden('user_id', $user_id);?>
<?php echo form_submit(array('value'=>'Reset Password', 'class'=>'btn btn-lg btn-primary btn-block')); ?>
<?php echo form_close(); ?>
</div>
And these are the errors I'm getting:
A PHP Error was encountered
Severity: Notice
Message: Undefined property: Auth::$user_model
Filename: controllers/Auth.php
Line Number: 123
Backtrace:
File: /home/ubuntu/workspace/application/controllers/Auth.php
Line: 123
Function: _error_handler
File: /home/ubuntu/workspace/index.php
Line: 315
Function: require_once
2nd error:
A PHP Error was encountered
Severity: Error
Message: Call to a member function getUserInfoByEmail() on a non-object
Filename: controllers/Auth.php
Line Number: 123
Backtrace:
I have absolutely no clue what I'm doing wrong and I hope someone can help me.
Thanks!
Load user model in auth controller. You can load it in constructor or in the function.
class Auth extends CI_Controller{
function __construct(){
parent::__construct();
$this->load->model('user_model'); // load user model
}
public function forgot(){
// your code
}
In Function
class Auth extends CI_Controller{
public function forgot(){
$this->load->model('user_model'); // load user model
// your code
}
Not tested
You need to make sure that the user_model class is loaded from the controller. Like so:
class Auth extends CI_Controller {
function __construct() {
$this->load->model('user_model');
}
}
And be sure that you have the spelling/capitalization correct in the model class.
class User_Model extends CI_Model {
// rest of code
}
#frodo again.
First Error : in your controller code, you need to initialize model first than only you can use the model property.
public function forgot(){
// Changes required
$this->load->model('user_model');
$userInfo = $this->user_model->getUserInfoByEmail($clean);
}
Second Error :
if($userInfo->status != $this->status[1]){
$this->session->set_flashdata('flash_message', 'Your account is not in approved status');
redirect(site_url().'auth/login');
}
How you get the value of $this->status[1] variable. You can simply use if($userInfo->status != true).
Please change this code and let me know if you have any error.

The alert message is displaying without the login form

In the below codeigniter code i have placed the controller and view part.Now if a inactive tries to log the account it should display in active user along with login form .In my case the message is displaying without login and finally login forms disappear.
Controller:
function index()
{
$data['main_content'] = 'login_form';
$this->load->view('includes/template', $data);
}
function inactive()
{
echo"<script>alert('In active user');</script>";
}
function validate_credentials()
{
$this->load->model('membership_model');
$query = $this->membership_model->validate();
if($query) // if the user's credentials validated...
{
$data = array(
'username' => $this->input->post('username'),
'is_logged_in' => true
);
if($query->num_rows()>0){
$status = $query->row()->account_status;}
else {
$status = ''; }
if($status == 'active')
{
$this->session->set_userdata($data);
redirect('site1/members_area');
}
else //Account In active
{ $this->inactive(); }
}
else // incorrect username or password
{
$this->index();
}
}
view:
<?php $this->load->view('includes/header'); ?>
<link rel="stylesheet" type="text/css" href="<?php echo base_url();?>css/style1.css" />
<div id="login_form">
<h1>Login!</h1>
<?php
echo form_open('login/validate_credentials');
echo form_input('username', 'Username');
echo form_password('password', 'Password');
echo form_submit('submit', 'Login');
echo anchor('login/signup', 'Create Account');
echo form_close();
?>
</div><!-- end login_form-->
<?php $this->load->view('includes/footer'); ?>
I can't see where ve you called your view file in inactive() in controller??
function inactive()
{
echo"<script>alert('In active user');</script>";
$this->load->view('Your view with login form'); // this part
}
The most obvious (possible) mistake here is that you do not pass your posted data to $this->membership_model->validate();. Since you did not post the code to that function I can not be 100% sure, but I am willing to bet that this is the problem. The information is not passed, so the $query variable is not properly set, hence the error displays.
Why don't you try this:
function index($inactive_login = FALSE) {
$data['inactive_login'] = $inactive_login;
$data['main_content'] = 'login_form';
$this->load->view('includes/template', $data);
}
function validate_credentials() {
$this->load->model('membership_model');
$query = $this->membership_model->validate();
if($query) // if the user's credentials validated...
{
$data = array(
'username' => $this->input->post('username'),
'is_logged_in' => true
);
if($query->num_rows()>0){
$status = $query->row()->account_status;}
else {
$status = ''; }
if($status == 'active')
{
$this->session->set_userdata($data);
redirect('site1/members_area');
}
else //Account In active
{
$inactive_login = TRUE;
$this->index($inactive_login);
}
}
else // incorrect username or password
{
$this->index();
}
}
View:
<?php $this->load->view('includes/header'); ?>
<?php
if($inactive_login){
echo "<script>alert('In active user');</script>";
}
?>
<link rel="stylesheet" type="text/css" href="<?php echo base_url();?>css/style1.css" />
<div id="login_form">
<h1>Login!</h1>
<?php
echo form_open('login/validate_credentials');
echo form_input('username', 'Username');
echo form_password('password', 'Password');
echo form_submit('submit', 'Login');
echo anchor('login/signup', 'Create Account');
echo form_close();
?>
</div><!-- end login_form-->
<?php $this->load->view('includes/footer'); ?>

CI - show me what went wrong [duplicate]

This question already has answers here:
CI - show database error or fail
(2 answers)
Closed 9 years ago.
I've developed a simple login system which works OK but fails, and I need to know why.
QUESTION: How to show what is causing the fail?
Here's the database function:
function login($email,$password)
{
$this->db->where("email",$email);
$this->db->where("password",$password);
$query=$this->db->get("users");
if($query->num_rows()>0)
{
foreach($query->result() as $rows)
{
//add all data to session
$newdata = array(
'user_id' => $rows->id,
'user_name' => $rows->username,
'user_email' => $rows->email,
'logged_in' => TRUE,
);
}
$this->session->set_userdata($newdata);
return true;
}
return false;
}
And here's the logic:
public function login()
{
$this->load->library('form_validation');
// field name, error message, validation rules
$this->form_validation->set_rules('email', 'Your Email', 'trim|required|valid_email');
$this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[4]|max_length[32]');
if($this->form_validation->run() == FALSE)
{
$this->signin();
}
else
{
$email=$this->input->post('email');
$password=md5($this->input->post('pass'));
$result=$this->user_model->login($email,$password);
if($result)
{
$this->dash();
}
else
{
$data['title']= 'Login Error';
$this->load->view('nav/header', $data);
$this->load->view('login', $data);
$this->load->view('nav/footer', $data);
}
}
}
I know the error is happening as I redirect back to the login page if it fails and change the title text to show me (only in testing mode for right now). But how can I find out what is going wrong?
This is the check database function:
function login($email,$password)
{
$this->db->where("email",$email);
$this->db->where("password",$password);
$query=$this->db->get("users");
if($query->num_rows()>0)
{
foreach($query->result() as $rows)
{
//add all data to session
$newdata = array(
'user_id' => $rows->id,
'user_name' => $rows->username,
'user_email' => $rows->email,
'logged_in' => TRUE,
);
}
$this->session->set_userdata($newdata);
return true;
}
return false;
}
I assume all your php code is fine, then what you need is set custom form-validation-message for each input to know which input went wrong and echo them:
<?php echo validation_errors(); ?>
write below code in your view file
<section id="notification" >
<?php
if(validation_errors() !== '' ) {
echo "<div class='alert-msg error'>";
echo validation_errors();
echo "</div>";
}
$error = $this->session->flashdata('error');
$success = $this->session->flashdata('success');
if($error)
{
echo "<div class='alert-msg error'>";
echo $this->session->flashdata('error');
echo "</div>";
}
if($success)
{
echo "<div class='alert-msg success'>";
echo $this->session->flashdata('success');
echo "</div>";
}
?>
</section>
and set success/error message conditionally in flash data in controller ( see below)
if($result) {
    $this->dash();
$this->session->set_flashdata('success', 'Login successfully.');
 } else {
     $this->session->set_flashdata('error', 'Login failed');
}
Read more Flashdata in CI
For your changed answer:
use below logic in your model
$qry = $this->db->get_where('users', array('username' => $this->_username ));
if ($qry->num_rows() == 1) {
$user = $qry->row_array();
$submitted_pass = md5($this->_password);
$db_pass = $user['password'];
if ($submitted_pass === $db_pass) {
return $user;
} else {
// wrong username/password
$this->session->set_flashdata('error', $this->errorList[10]);
return FALSE;
}
} else {
// no such username exist
$this->session->set_flashdata('error', $this->errorList[15]);
return FALSE;
}

Use CodeIgniter (MVC) to Connect Form to Database

My assignment is to use CodeIgniter (an MVC framework) and connect the form that's in the view to the database. I have done most of the code, and I believe most of it is correct. I finally got the view page (form) to load, but I cannot get the Register function in the controller to load. Does anyone see any errors in my code? It would help me a great deal.
form.php (view):
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title><?php //echo $title;?></title>
</head>
<body>
<h1>Register for a Dorm</h1>
<form method="post"
action="http://ispace.ci.fsu.edu/~trm07/assignment4/index.php/controller/register/">
<fieldset>
<label>First Name</label>
<input type="text" name="first_name"/>
<label>Last Name</label>
<input type="text" name="last_name"/>
</fieldset>
<label>Undergraduate Level:</label>
<?php
//dropdown list for level
echo '<select name="level">';
$level = array('Freshman','Sophomore', 'Junior', 'Senior');
foreach ($level as $selection) {
echo '<option value="'.$selection.'">'.$selection.'</option>';
}
echo '</select>';
?>
<label>Gender:</label>
<?php
//dropdown list for gender
echo '<select name="gender">';
$gender = array('Male','Female');
foreach ($gender as $gend_selection) {
echo '<option
value="'.$gend_selection.'">'.$gend_selection.'</option>';
}
echo '</select>';
//radio buttons for dorms
$requested_dorm = array('Landis','Salley','DeGraff','Cawthon','Reynolds');
echo("<fieldset><legend>Requested Dorm</legend>");
foreach ($requested_dorm as $dorm_names){
echo "<input type='radio' name='dorm_name' value='$dorm_names' />
$dorm_names <br />";
}
?>
<br><input type="submit" value="Register">
</body>
</html>
controller.php
<?php
class Controller extends CI_Controller {
function index()
{ //$data['title'] = "Register for a Dorm";
$this->load->view('form');
}
function show()
{
$this->load->model('model');
$dorms = $this->model->get_dorms();
foreach($dorms as $dorm){
if($dorm['dorm_name'] == $dorm_name)
$chosen_dorm = $dorm['dorm_name'];
}
}
function register()
{
$this->load->library('form_validation');
$view_data = array('message' => '');
//If the form was submitted, process it
if (count($_POST) > 0)
{ $dorm_name = $this->input->post('dorm_name');
$first_name = $this->input->post('first_name');
$last_name = $this->input->post('last_name');
$level = $this->input->post('level');
$gender = $this->input->post('gender');
{
//Validate the input
$this->form_validation->set_rules('first_name', 'First Name',
'required|strip_tags|trim');
$this->form_validation->set_rules('last_name', 'Last Name',
'required|strip_tags|trim');
$val_result = $this->form_validation->run();
//Add the data to the database
if ($val_result == TRUE)
{
$this->load->model('model');
$db_result = $this->model->add_student_to_dorm($_POST['dorm_name'],
$_POST['first_name'], $_POST['last_name'], $_POST['level'], $_POST['gender']);
if ($db_result == TRUE)
{
$view_data['message'] = "Added student to the dorm!";
//$view_data['message'] = "Added" . "$_POST['first_name']" . " " .
"$_POST['last_name']". " to " . "$_POST['dorm_name']" . " hall.";
}
else
{
$view_data['message'] = "An error occured adding the student to the dorm!";
}
}
}
$this->load->view('form',$view_data);
//$this->load->model('model');
//$this->model->get_students();
}
}
}
?>
model.php:
<?php
class Model extends CI_Model {
//function to take student info posted from form, and adds to database
public function add_student_to_dorm()
{
$this->load->database($dorm_name, $first_name, $last_name, $level, $gender);
$data = array
(
'dorm_name' =>$dorm_name,
'student_fname' => $first_name,
'student_lname' => $last_name,
'student_level' => $level,
'student_gender' => $gender,
);
$result = $this->db->insert('student', $data);
return $result;
}
//get dorm table results in an array from database, return its rows
public function get_dorms()
{
$this->load->database();
$dorms = $this->db->get('dorm');
$rows = $dorms->result_array();
return $rows;
}
//get student table results in an array from database, return its rows
public function get_students()
{
$this->load->database();
$students = $this->db->get('student');
$stu_rows = $students->result_array();
return $stu_rows;
}
}
?>
Here you called add_student_to_dorm() function in the controller page with parameters but in model you doesnot take that parameters that is
$db_result = $this->newmodel->add_student_to_dorm($_POST['dorm_name'],
$_POST['first_name'], $_POST['last_name'], $_POST['level'], $_POST['gender']);
this is the function in controller but your model is only have
public function add_student_to_dorm() no variables So change
public function add_student_to_dorm() to
public function add_student_to_dorm($dorm_name, $first_name, $last_name, $level, $gender)
and also change
$this->load->database($dorm_name, $first_name, $last_name, $level, $gender); to
$this->load->database(); in model then it is working

Categories