I want to display current user info from database after login.
Here is my code.
Controller 1 (Welcome)
public function getValues() {
$this->load->model('display_model');
$result=$this->display_model->authenticateUser();
if($result){
$this->session->set_userdata('id', $result['id']);
redirect('/member/home/');
}
else
redirect('/welcome/');
Controller 2 (member)
public function __construct()
{
// Call the CI_Model constructor
parent::__construct();
if($this->session->userdata('id')==NULL)
{
redirect('/welcome/');
}
}
public function home() {
$this->load->view('member_home');
}
Model
public function authenticateUser(){
$name =$_POST['name'];
$password=$_POST['password'];
$where=array('name'=>$name,
'password'=>$password);
return $this->db->select('name, password, id')
->from('member')
->where($where)
->get()->row_array();
View 1 (login_view)
<h1>Member Login Form</h1>
<?php echo validation_errors(); ?>
<?php echo form_open('Welcome/getValues'); ?>
Username: <br/>
<input type="text" name="name" /> <br>
Password: <br>
<input type="password" name="password" /> <br>
<input type="submit" value="Login" name="submit"/>
</form>
View 2: After login view (member_home)
<?php
foreach($result as $row){
?>
<li><?php echo $row['first_name'].' '.$row['last_name'];?>
<br/><strong>Email: </strong><?php echo $row['email'];?>
</li>
Now error shows
Message: Undefined variable: result
How to solve it Need Help.. Thanks in Advance
You are not passing the $result value to your home view update the code as follows:
Controller 1:
public function getValues() {
$this->load->model('display_model');
$result=$this->display_model->authenticateUser();
if($result){
$this->session->set_userdata('id', $result['id']);
redirect(member/home/$result['id']);
}
else
redirect('/welcome/');
Controller 2:
public function __construct()
{
// Call the CI_Model constructor
parent::__construct();
if($this->session->userdata('id')==NULL)
{
redirect('/welcome/');
}
}
public function home($id = '') {
$data['id'] = $id;
$this->load->view('member_home',$data);
}
NOTE:
you must change the query result from row_array() to result_array() as you are using foreach on the view
Related
please help me... My controller for registration and login is not working. Whenever I input the data in either login or register it will back to register and login view and not the index/home nor the data that I input enter mysql.
I create it like when I success in inputting the data on register it will direct to login then when you login it will direct to home. Other is login, when I login it will direct to home if it can login.
Controller: Member.php
class Member extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->library(array('session', 'form_validation'));
$this->load->helper(array('url', 'form'));
$this->load->model("Member_model");
}
public function index() {
$this->load->view('front/login');
}
public function Login() {
$this->load->view('front/login');
}
public function Register() {
$this->load->view('front/register');
}
public function profile() {
if ($_SESSION['user_logged'] == FALSE) {
$this->session->set_flashdata("error","Please login first to view");
redirect('Member/Login');
}
$this->load->view('front/home');
}
}
Controller: Register.php
class Register extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->library(array('session', 'form_validation'));
$this->load->helper(array('url', 'form'));
$this->load->model("Member_model");
}
public function registerMember() {
//validate the data taken through the register form
$this->form_validation->set_rules('username','Username','required|is_unique[member.username]');
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
$this->form_validation->set_rules('password', 'Password', 'trim|required|md5|min_length[6]');
$this->form_validation->set_rules('conf_password', 'Confirm Password', 'trim|required|min_length[6]|matches[password]');
if ($this->form_validation->run() == TRUE) {
//load the model to connect to the db
$this->load->model('Member_model');
$this->Member_model->insertMember();
//set message to be shown when registration is completed
$this->session->set_flashdata('success','You are registered!');
redirect('Member/Login');
} else {
$this->load->view('front/register');
}
}
}
Controller: Login.php
class Login extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->library(array('session', 'form_validation'));
$this->load->helper(array('url', 'form'));
$this->load->model("Member_model");
}
public function loginMember() {
$this->form_validation->set_rules('username','Username','required');
$this->form_validation->set_rules('password','Password','required');
if ($this->form_validation->run() == FALSE) {
$this->load->view('front/login');
} else {
$this->load->model('Member_model');
$reslt = $this->Member_model->checkLogin();
if ($reslt != false) {
//set session
$username = $_POST['username'];
$password = sha1($_POST['password']);
//fetch from databse
$this->db->select('*');
$this->db->from('member');
$this->db->where(array('username' => $username , 'password' => $password));
$query = $this->db->get();
$member = $query->row();
//if use exists
if ($member->username) {
//login message
$this->session->set_flashdata("success","You are logged in");
//set session variables
$_SESSION['user_logged'] = TRUE;
$_SESSION['username'] = $member->username;
//redirect
redirect('Member/profile','refresh');
}
} else {
//wrong credentials
$this->session->set_flashdata('error','Username or Password invalid!');
redirect('Member/Login');
}
}
}
//logging out of a user
public function logoutMember() {
unset($_SESSION);
redirect('Member/Login');
}
}
Model: Member_model.php
class Member_model extends CI_Model {
public function insertMember () {
//insert data
$data = array(
//assign data into array elements
'username' => $this->input->post('username'),
'email' =>$this->input->post('email'),
'password' => sha1($this->input->post('password'))
);
//insert data to the database
$this->db->insert('member',$data);
}
public function checkLogin() {
//enter username and password
$username = $this->input->post('username',TRUE);
$password = sha1($this->input->post('password',TRUE));
//fetch data from database
$this->db->where('username',$username);
$this->db->where('password',$password);
$res = $this->db->get('member');
//check if there's a user with the above inputs
if ($res->num_rows() == 1) {
//retrieve the details of the user
return $res->result();
} else {
return false;
}
}}
View:
Register.php
<body class="background-login">
<div class="main-w3layouts wrapper">
<h1> SignUp </h1>
<div class="main-agileinfo">
<div class="agileits-top">
<form method="post" action="<?php echo site_url('register/registerMember'); ?>" >
<input class="text" type="text" id="username" name="username" placeholder="Enter a username">
<input class="text email" type="email" id="email" name="email" placeholder="Enter your email">
<input class="text" type="password" id="password" name="password" placeholder="Enter a password">
<input class="text w3lpass" type="password" id="conf_password" name="conf_password" placeholder="Confirm your password">
<div class="wthree-text">
<label class="anim">
<input type="checkbox" class="checkbox" required="">
<span>I Agree To The Terms & Conditions</span>
</label>
<div class="clear"> </div>
</div>
<input type="submit" value="SignUp">
</form>
<p>Already have an Account? Login Now!</p>
</div>
</div>
Login.php
<body class="background-login">
<div class="main-w3layouts wrapper">
<h1> SignIn </h1>
<div class="main-agileinfo">
<div class="agileits-top">
<form method="post" action="<?php echo site_url('Login/loginMember'); ?>" >
<input class="text" type="text" id="username" name="username" placeholder="Your username"><br>
<input class="text" type="password" id="password" name="password" placeholder="Your password">
<input type="submit" value="Login"/>
</form>
<p>Don't have an Account? SignUp NOW!</p>
</div>
</div>
I even chop my code into part like this, but the problem still the same... Is just like the if form_validation->run is not running and just got cut to else...
So the problem is:
When I input data it will not enter the data or redirect to another page.
*register -> it will direct to register after i submit the data
What I want is when I submit the data it will direct to login.
*login -> it will direct to login after i submit the data
What I want is when I submit the data it will direct to home.
-> result ->
I also had this case . I solved it by passing $this in to run()
if ($this->form_validation->run($this) == TRUE)
You can pass array in where condition in checkLogin function
$where_array = array('username' => $username,'password' => $password);
$this->db->where($where_array);
$res = $this->db->get('member');
Hope it help you too!
You can not use the form_open function and html form tag at the same time, so remove anyone from it and pass the whole path in the action.
If you use form_open function then please add the form_close function.
in your register and login view
<?= form_open() ?>
<form action="#" method="post">
you added this. this is wrong.at a same time you open two form you need to remove a line.and add some action to form for example
<form action="<?= base_url('yourControllerName/YourMethodname')?>" method='post'></form>
and second thing in Member.php Controller you added this line
if ($this->form_validation->run() === FALSE){
Some code
}
this is wrong you need this
if ($this->form_validation->run() == FALSE)
please check and ping me......
Make sure your base_url in config.php is not null.
In register.php remove <?=form_open('member/login')?> and <?= form_close() ?>
Instead add, <form method="post" action="<?php echo site_url('Member/register'); ?>" >
and
</form>
redirect your page:
//login
if ($this->form_validation->run() === TRUE)
{
$username = $this->input->post('username');
$email = $this->input->post('email');
$password = $this->input->post('password');
$user= $this->member_model->create_user();
if($user >0){
redirect('front/home');
} else {
redirect('front/login');
}
}
you can same as in singup
I am new one to codeigniter. I need to insert the data in the database for that i create a controller on the name Home.php, below is that code;While i am running i am getting the error like Message: Undefined property: Home::$Yes.Kindly help please,thank in advance
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Home extends CI_Controller{
public function index()
{
$this->load->database();
$this->load->model('yes');
}
public function savedata()
{
$this->load->view('demo');
if($this->input->post('submit'))
{
$name=$this->input->post('name');
$email=$this->input->post('email');
$content=$this->input->post('content');
$this->Yes->saverecords($name,$email,$content);
echo "Records Saved Successfully";
}
}
}
Here the view pahe at name - demo.php
<html>
<head>
<title></title>
</head>
<body>
<form method="post" action="" enctype="multipart/form-data"
id="User">
<h2 align="center">Student Marks</h2>
<h3>Name:</h3>
<input type="text" name="name" />
<h3>Email ID</h3>
<input type="text" name="email" />
<h3>Content </h3>
<input type="text" name="content" />
<button type="submit" value="submit" name="submit" >Submit</button>
<button type="reset" value="Reset" >Reset</button>
</form>
</body>
</html>
here is the model page at Yes.php
<?php
class Yes extends CI_Models
{
function saverecords($name,$email,$content)
{
$query="insert into news values('$name','$email','$mobile')";
$this->db->query($query);
}
}
first of all you have to load model in your controller.
defined('BASEPATH') OR exit('No direct script access allowed');
class Home extends CI_Controller{
function __construct() {
parent::__construct();
$this->load->model('Yes');
}
public function savedata()
{
if($this->input->post('submit'))
{
insert_array=array(
'name' => $this->input->post('name'),
'email' => $this->input->post('email'),
'content' => $this->input->post('content')
);
$data_id = $this->Yes->saverecords($insert_array);
if($data_id >0){
echo "Records Saved Successfully";
}
}
}
}
In Model
function saverecords($insert_array) {
if ($this->db->insert('news', $insert_array)) {
return $this->db->insert_id();
}
return 0;
}
Hope this will help you
In controller load database and model in __construct like this , your are adding it to only index method
public function __construct()
{
parent::__construct();
$this->load->database();
$this->load->model('yes');
}
public function index()
{
}
public function savedata()
{
if($this->input->post('submit'))
{
$name = $this->input->post('name');
$email = $this->input->post('email');
$content = $this->input->post('content');
$data = ['name' => $name,'email' => $email,'content' => $content];
$insert_id = $this->yes->saverecords($data);
if ($insert_id)
{
echo "Records Saved Successfully";
}
}
$this->load->view('demo');
}
Second
Is $this->load->view('demo'); your form in savedata() method then the form url is ok but if not
Form action should redirect to savedata method because you are accessing post value to in it
<form method="post" action="<?=base_url('home/savedata');?>" enctype="multipart/form-data">
Third Your Model should be like this:
<?php
class Yes extends CI_Models
{
function saverecords($data)
{
$this->db->insert('table_name', $data);
return $this->db->insert_id();
}
}
This question already has answers here:
How to Inserting Form values into mysql database using codeigniter [closed]
(3 answers)
Closed 6 years ago.
I have a contact list on my mySQL database. The columns on my database are name, email and phone_number. Using codeigniter. I know the code I need to insert the data from the form into the database but I can't figure out where to put it into the code. I had the code below in a separate document called form.php but that just kept giving me errors anytime I hit submit. Hence why form.php is in the view.php form.
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone_number'];
$sql = "INSERT INTO data (name, email, phone_number) VALUES ('$name', '$email', '$phone')";
controller.php:
<?php
class controller extends CI_Controller
{
public function index()
{
$this->load->model('model');
$data['info'] = $this->model->getData();
$this->load->view('view', $data);
}
}
?>
model.php:
<?php
class model extends CI_Model
{
public function getData()
{
$query = $this->db->get('data');
return $query->result();
}
}
?>
view.php:
<!DOCTYPE html>
<html>
<head>
<title>Contact List</title>
</head>
<body>
<form action="form.php" method="post">
<p>Name: <input type="text" name="name"></p>
<p>Email: <input type="text" name="email"></p>
<p>Phone Number: <input type="text" name="phone_number"></p>
<input type="submit" value="Submit"><br><br>
<input type="button" onClick="history.go(0)" value="Refresh">
</form>
<br>
<?php
foreach ($records as $rec) {
echo "Name: ".$rec->name."<br>";
echo "Email: ".$rec->email."<br>";
echo "Phone Number:".$rec->phone_number."<br><br>";
}
?>
</body>
</html>
Any help would be appreciated.
Your main problem is bad understanding of MVC arhitecture. If you are new, take time and explore it.
-View
<!DOCTYPE html>
<html>
<head>
<title>Contact List</title>
</head>
<body>
<?php echo form_open('controller/insert');?>
<p>Name: <input type="text" name="name"></p>
<p>Email: <input type="text" name="email"></p>
<p>Phone Number: <input type="text" name="phone_number"></p>
<input type="submit" value="Submit"><br><br>
<input type="button" onClick="history.go(0)" value="Refresh">
<?php echo form_close();?>
<br>
<?php
foreach ($info as $rec) {
echo "Name: ".$rec->name."<br>";
echo "Email: ".$rec->email."<br>";
echo "Phone Number:".$rec->phone_number."<br><br>";
}
?>
</body>
</html>
CONTROLLER
<?php
class controller extends CI_Controller
{
function __CONSTRUCT(){
parent::_CONSTRUCT();
$this->load->helper('file');
$this->load->helper('form');
$this->load->helper('url');
$this->load->model('model');
}
public function index()
{
$this->load->model('model');
$data['info'] = $this->model->getData();
$this->load->view('view', $data);
}
public function insert() {
$data = array (
'name' => $this->input->post('name'),
'email' => $this->input->post('email'),
'phone_number' => $this->input->post('phone_number')
);
$this->model->insert_data($data);
$this->load->view('view');
}
}
?>
MODEL
<?php
class model extends CI_Model
{
function __CONSTRUCT(){
parent::__CONSTRUCT();
$this->load->database('your_databse_name');
$this->load->library('db'); // optionali you could set it on autoload
}
public function getData()
{
$query = $this->db->get('data');
return $query->result();
}
public function insert_data($data){
$this->db->insert('your_data_table', $data);
}
}
?>
I think this should help you.
If I understand your question correctly, you're trying to submit a form. But you're submitting it to form.php which does not exist.
To elaborate further: In traditional PHP you would submit your form to a new page or the same page and check for $_POST values in that page. Since Codigniter is an MVC framework, you would post your data back to a controller. Which controller doesn't matter.
In your controller you load a model where you create a function to write or get data from or to the database. However, the model is less used nowadays. I'm not sure why because it keeps things organized.
After the controller has processed the data, a new view is loaded. In your case you would create a new view named form.php and load the view via the controller method.
The correct way to do this would be something like this:
<!DOCTYPE html>
<html>
<head>
<title>Contact List</title>
</head>
<body>
<form action="controller/form" method="post">
<p>Name: <input type="text" name="name"></p>
<p>Email: <input type="text" name="email"></p>
<p>Phone Number: <input type="text" name="phone_number"></p>
<input type="submit" value="Submit"><br><br>
<input type="button" onClick="history.go(0)" value="Refresh">
</form>
<br>
<?php
foreach ($records as $rec) {
echo "Name: ".$rec->name."<br>";
echo "Email: ".$rec->email."<br>";
echo "Phone Number:".$rec->phone_number."<br><br>";
}
?>
</body>
</html>
Your controller should like this:
<?php
class controller extends CI_Controller
{
public function index()
{
$this->load->model('model');
$data['info'] = $this->model->getData();
$this->load->view('view', $data);
}
public function form() {
$this->load->model('model');
$data = array(
'name' => $_POST['name'],
'email' => $_POST['email'],
'phone_number' => $_POST['phone_number'] // should be exact table column name for this to work
);
$this->model->insertData($data);
$this->load->view('view', $data);
}
}
?>
And in your model:
<?php
class model extends CI_Model
{
public function getData()
{
$query = $this->db->get('data');
return $query->result();
}
public function insertData($data)
{
return $this->db->insert('data', $data);
}
}
?>
**After you copied my answer, you supplied invalid argument into foreach statement.
Should be:
foreach ($info as $rec) {
Instead of yours
foreach ($records as $rec) {
Create method in model public function insert($data)
public function insert($data){
$sql = "INSERT INTO data (name, email, phone_number) VALUES ('$data['name']', '$data['email']', '$data['phone_number']')";
$this->db->query($sql);
}
When i login to the admin page i got the error 404 Page Not Found.The page you requested was not found.
I am tring to login to the admin page in the following code:
Controller:
public function index()
{
$data = $this->data;
$this->load->view('admin/index.php',$data);
}
public function login()
{
$data = $this->data;
$username=$this->input->post("username");
$password=$this->input->post("password");
print_r($username); die();
$this->load->model('admin/grocery_crud_model');
$res=$this->grocery_crud_model->check_login($username,$password);
if($res==1)
{
$this->load->view('admin/main.php',$data);
}
else
{
$data['error']="Invalid Username or Password";
$this->load->view('admin/index.php',$data);
}
}
public function home()
{
$data = $this->data;
$this->load->view('admin/index.php',$data);
}
Grocery crud model:
public function check_login($username,$password)
{
$query=$this->db->query(" select * from tbl_register where username='".$username."' and password='".$password."'");
return $query->num_rows() ;
}
View:
<form name="login" action="<?php echo site_url('admin/admin/login');?>" method="post">
<div class="col-md2"></div>
<div class="col-md8 lgmid">
<div class="error" style="margin-left:10px; margin-top:35px;"><?php //echo $error;?></div>
<div class="lg"><label><b>Username</b></label> <input type="text" name="username" class="textbox"></div>
<div class="lg"><label><b>Password</b></label> <input style="margin-left:2px" type="password" name="password" class="textbox"><br/></div>
<div align="center"><input type="submit" class="lgbtn" value="Submit" /></div>
</div>
<div class="col-md2"></div>
</form>
Here in model the table used is tbl_register. Is there any problem with the model .Please provide solution for this issue.
You cant load view like this
$this->load->view('admin/index.php',$data); //wrong
you have to load without file extension
$this->load->view('admin/index',$data); //correct
so folder structure would be
application
controllers
model
view
admin
index
and in Model
public function check_login($username,$password)
{
$query=$this->db->query(" select * from tbl_register where username='$username' and password='$password'");
$result = $query->result_array();
$count = count($result);
return $count;
}
EDIT 01
and in form action
Change this to
action="<?php echo site_url('admin/admin/login');?>"
this
action="<?php echo base_url().'admin/admin/login'?>"
in order to use base_url() load url library in autoload.php
remove this
$config['base_url'] = 'http://localhost/ASoft/Projects/AutoGadi2Amy';
$config['base_url'] = '';
just keep empty
I'm new to CodeIgniter.
At the moment I have a register.php(VIEW) and a register.php(CONTROLLER). The register.php(VIEW) contains a simple form and from this form I am trying to pass data to the controller in order to insert it to the database. Simple.
Whenever I load the view all I seem to be getting is different error messages in relation to the variables and functions, also errors on the line which I try to load the view.
I'm simply asking:
Is this the correct way to be using controllers and views together?
How can I fix this current problem?
Below are the two files:
register.php (VIEW)
<htmL>
<body>
<form method="post" action="controllers/register.php">
<input type="text" name="email">
<input type="text" name="name">
<input type="password" name="password">
<select id="userLevel" name="userLevel">
<option value="2">Job Seeker</option>
<option value="3">Employer</option>
</select>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</htmL>
register.php (CONTROLLER)
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Users extends CI_Controller{
public function __construct(){
public $email;
public $name;
public $password;
public $userLevel;
$this->email = $_POST['email'];
$this->name = $_POST['name'];
$this->password = $_POST['password'];
$this->userLevel = $_POST['userLevel'];
}
public function createuser() {
if( filter_var($this->email, FILTER_VALIDATE_EMAIL) ) {
$this->db->set('email', $this->email);
$this->db->set('name', $this->name);
$this->db->set('password', $this->password);
$this->db->set('userLevel', $this->userLevel);
$this->db->insert('users');
}
}
$this->load->view('register');
}
?>
Your controller should look like this:
class Users extends CI_Controller{
public function __construct(){
parent::__construct();
}
public function createuser() {
if($this->input->post(null)){
$data = array();
$data['email'] = $this->input->post('email');
$data['name'] = $this->input->post('name');
$data['password'] = $this->input->post('password');
$data['userLevel'] = $this->input->post('userLevel');
$this->db->insert('users', $data);
}
$this->load->view('register');
}
}
Instead of writing <form method="post" action="controllers/register.php"> write <?=form_open('user/createuser')?>
You need to do like this. It is MVC and more clear
VIEW
<htmL>
<body>
<?php echo form_open('controllers/createuser'); ?>
<input type="text" name="email">
<input type="text" name="name">
<input type="password" name="password">
<select id="userLevel" name="userLevel">
<option value="2">Job Seeker</option>
<option value="3">Employer</option>
</select>
<input type="submit" name="submit" value="Submit">
<?php echo form_close(); ?>
</body>
</htmL>
Controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Users extends CI_Controller{
public function __construct(){
$this->load->helper('form');
}
public function createuser() {
$data['email'] = $this->input->post['email'];
$data['name'] = $this->input->post['name'];
$data['password'] = $this->input->post['password'];
$data['userLevel'] = $this->input->post['userLevel'];
if($this->input->post('submit')) {
// Here you can validate data if you want
$this->user_model->insert($data);
redirect('users/success');
}
$this->load->view('register');
}
function success() {
echo "You add user";
}
}
?>
Model
class User_model extends CI_model {
public function __construct() {
parent:: __construct();
}
function add($data) {
$this->db->insert('users', $data); // table name users
}
}