Hello i'm trying to show up the alert after validation succes ,but the alert not showing up .
code wrong or what ??
public function dashboard()
{
$this->form_validation->set_rules('username', 'Username', 'trim|required|min_length[5]');
$this->form_validation->set_rules('pass', 'Password', 'trim|required|min_length[5]');
if($this->form_validation->run() != false){
echo "<script>
Swal.fire('Login Success')
</script>";
}else{
$this->load->view('login');
}
}
Are there any errors logged? I usually close php with then execute the Javascript then open it again.
public function dashboard()
{
$this->form_validation->set_rules('username', 'Username', 'trim|required|min_length[5]');
$this->form_validation->set_rules('pass', 'Password', 'trim|required|min_length[5]');
if($this->form_validation->run() != false){
?>
<script>
Swal.fire('Login Success');
</script>
<?php
}else{
$this->load->view('login');
}
}
Related
Hi guys I have a User controller and User_model model. I want to be able to retrieve and display a logged in users email and phone number from the database to a view after the user is logged in. any idea how I could go about this would be appreciated and if codes could be written to demonstrate I would be very happy.
MODEL
public function login($username, $password){
//validation
$this->db->select('id, email, username');
$this->db->where('username', $username);
$this->db->where('password', $password);
$this->db->where('status', 1);
$result = $this->db->get('users');
if($result->num_rows() == 1){
return $result->row(0)->id;
} else {
return FALSE;
}
}
public function get_user($username){
$this->db->where('username', $username);
$query = $this->db->get('users');
return $query->result();
}
CONTROLLER:
public function login(){
$data['title'] = 'Login';
$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('templates/header');
$this->load->view('users/login', $data);
$this->load->view('templates/footer');
} else {
// fetching user
$username = $this->input->post('username');
//Encrypted password
$password = md5($this->input->post('password'));
//login user
$user_id = $this->user_model->login($username, $password);
if($user_id){
//creating session
$user_data = array(
'user_id' => $user_id,
'username' => $username,
'logged_in' => TRUE,
);
$this->session->set_userdata('user_data',$user_data);
// Set message to be sent
$this->session->set_flashdata('user_login', 'Welcome');
redirect('posts');
} else {
// Set message to be sent
$this->session->set_flashdata('login_fail', 'Login Failed');
redirect('users/login');
}
}
}
public function get_user()
{
if($this->session->userdata('logged_in')){
$username = $this->session->userdata('username');
$data['results'] = $this->user_model->get_user($username);
$this->load->view('templates/header');
$this->load->view('users/login', $data);
$this->load->view('templates/footer');
}
}
There is basic problem in your Controller
Session Data Problem: In your Controller you storing all array data in CodeIgniter Session:
the 'user_data' would work like array key, and all other array will be assign as keys data;
$this->session->set_userdata('user_data', $user_data);
and you retrieving/checking the session data by using $this->session->userdata('logged_in') and $this->session->userdata('username'), It's wrong my friend. You can get user data session by $this->session->userdata('user_data')['username'] or $this->session->userdata['user_data']['username'] ...
Because the session would be like;
Array
(
[__ci_last_regenerate] => 1499791562
// This is the array key 'user_data' where your array data stores
[user_data] => Array
(
[user_id] => 1
[username] => scott
[email] => scott.dimon#example.com
[phone_number] => 1234567890
[first_name] => Scott
[logged_in] => 1
)
)
So, you have to have use 'user_data' with session to get your data
One thing I would like to share with everyone, Always Read The Docs and manual Carefully. Believe me if you read before the start, your code would be more nicer and cleaner... Ha ha ha ha ha.. ;) :|
When you login if you set the users_id in session you can get the information like
Read manual also
https://www.codeigniter.com/user_guide/database/results.html#result-rows
https://www.codeigniter.com/user_guide/general/views.html#adding-dynamic-data-to-the-view
Make sure you autoload session, and database.
Examples ONLY below.
Filename: User_model.php
class User_model extends CI_Model {
public function get_user($id)
{
$this->db->where('user_id', $id);
$user_query = $this->db->get('yourtable');
return $user_query->row_array();
}
}
Filename: Dashboard.php
Controller
<?php
class Dashboard extends CI_Controller {
public function __construct()
{
parent::__construct();
if (!$this->session->userdata('user_id'))
{
redirect('logoutcontroller');
}
$this->load->model('user_model');
}
public function index()
{
$userdata = $this->user_model->get_user($this->session->userdata('user_id'));
/** You can use what you want example
$data['email'] = $userdata['email'];
**/
$data['username'] = $userdata['username'];
$this->load->view('some_view', $data);
}
}
View
<?php echo $username;?>
You can use session to carry the logged in user detail.
This is your model code:
//In your model
$query = $this->db
->select('id,email,phone')
->where(['username' => $username, 'password' => $password])
->where('status','1')
->get('users');
$user_data = $query->row_array();
if (!empty($user_data)) {
return $user_data;
} else {
return FALSE;
}
In side the controller where you get the user data if username & password is correct. Here you can put the user data on session:
//In Side Controller
$user_data = $this->user_model->login($username, $password);
if(isset($user_data) && !empty($user_data)){
// you can directly add the `$user_data` to the session as given billow.
// set user data in session
$this->session->set_userdata('user_data', $user_data);
Now after putting a data on session you can retrive it any where, on any view or in side morel, controller.
//retrive the user data in any view
//To echo in view Inside your view code.
<?php
$session_data = $this->session->userdata('user_data');
$user_email = $session_data['email'];
$user_phone = $session_data['phone'];
$user_id = $session_data['id'];
?>
<?= $user_phone ?> OR <?php echo $user_phone; ?>
<?= $user_email ?> OR <?php echo $user_email; ?>
On Your $this->load->view('users/login', $data); this view. Where the HTML & PHP code placed.
Example:
<html>
// Your View Page
</body>
<?php
$session_data = $this->session->userdata('user_data');
$user_email = $session_data['email'];
$user_phone = $session_data['phone'];
$user_id = $session_data['id'];
?>
<h1> Logged In User Email: <?= $user_email ?> </h1>
<h1> Logged In User Phone: <?= $user_phone ?> </h1>
<body>
</html>
Note: Once You save the user data inside the session then you don't need to pass that data to the view form controller. You just need to echo it where you need that.
You need to load session library first. like
$this->load->library('session');
Then after you can save your data into session like,
$newdata = array(
'username' => 'johndoe',
'email' => 'johndoe#some-site.com',
'logged_in' => TRUE
);
$this->session->set_userdata($newdata);
Then where ever you require at controller you can retrive session data like,
$data['session_data'] = $this->session->all_userdata();
and then pass to your view,
$this->load->view('data', $data);
and then access that data into your view with the key,
<?= $session_data['username']; ?>
I hope it helps,
Does this answer your question?
public function login($username, $password){
$db = $this->db;
//validation
$db->select('id, email, username');
$db->where('username', $username);
$db->where('password', $password);
$db->where('status', 1);
$result = $db->get('users')->row_array();
return empty($result['id']) ? false : $result['id'];
}
With a unique index on username you won't need to check the number of rows as it will be limited to 1.
if($user_id){
//creating session
$user_data = array(
'user_id' => $user_id,
'username' => $username,
'logged_in' => TRUE,
);
$this->session->set_userdata($user_data);
// Set message to be sent
$data['session_data'] = $this->session->all_userdata();
$this->session->set_flashdata('user_login', 'Welcome');
$this->load->view('posts', $data);
//redirect('posts');
}
else {
// Set message to be sent
$this->session->set_flashdata('login_fail', 'Login Failed');
redirect('users/login');
}
}
at the view,
<?php print_r($session_data); ?>
if you get your session data into print,
you can display it like,
<?= $session_data['user_id']; ?>
****Modal**
//user login**
function userlogin($data)
{
$condition = "username =" . "'" . $data['username'] . "' AND " . "password =" . "'" . $data['password'] . "' AND " . "status = '1'";
$this->db->select("*");
$this->db->from("user");
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 1)
{
return $query->result();
}
else {
return false;
}
}
And in your Controller check
if($this->modal_name->login()==false)
{
//redirect user to login page
}
else
{
$data['details'] = $this->modal_name->login();
$this->load->view("post",$data);
}
View
foreach($details as $detail)
{
echo $detail->id;
echo $detail->username;
}
My controler cod is:
function register()
{
if(isset($_POST['register'])){
$this->form_validation->set_rules('username','Username','required');
$this->form_validation->set_rules('email','Email','required');
$this->form_validation->set_rules('password','Password','required');
//
if($this->form_validation->run () == true){
echo 'Form Validate';
$data = array(
'username'=>$_POST['username'],
'email'=>$_POST['email'],
'password'=>strtoupper(hash('whirlpool',$_POST['password']))
);
$this->db->insert('accounts',$data);
$this->load->model("usuarios_model");
if($this->usuarios_model->check_user_exist($data['username'])){
echo "already user exist";
}{
$this->db->insert('accounts',$data);
redirect("painel/index");
}
}
}
$this->load->view("painel/register");
}
[![enter image description here][2]][2]
It registers an user even though the username already exists.
Where is the mistake?
You can use is_unique rule in your form_validation library.
$this->form_validation->set_rules('username','Username','required|is_unique[table.column]');
You have mistake in your model in where condition it will be small later of username but you used Username.
use this code in your model.
function check_user_exist($username){
$this->db->wehre('username',$username);
$this-db->from('accounts');
$query= $this->db->get();
if($query->num_rows() > 0){
return true;
}else{
return false;
}
}
and also controller data insert after user check:
if($this->usuarios_model->check_user_exist($data['username'])){
echo "already user exist";
}{
$this->db->insert('accounts',$data);
redirect("painel/index");
}
You can easily achieve this using call_back function in validation. From Codeigniter Docs
Controller
function register() {
if ($this->input->post('register')) {
$this->form_validation->set_rules('username','Username','required|callback_checkUserName');
$this->form_validation->set_rules('email','Email','required');
$this->form_validation->set_rules('password','Password','required');
//
if ($this->form_validation->run() == true) {
$data = array(
'username '=> $this->input->post('username'),
'email' => $this->input->post('email'),
'password' => strtoupper(hash('whirlpool', $this->input->post('password')))
);
$this->db->insert('accounts',$data);
echo 'success';
exit();
} else {
echo validation_errors(); die; // check errors
}
}
$this->load->view("painel/register");
}
// call back validate function
function checkUserName($userName){
if ($this->usuarios_model->checkUserexist($userName) == false) {
return true;
} else {
$this->form_validation->set_message('checkUserName', 'This userName already exist!');
return false;
}
}
MODEL
function checkUserexist($userName) {
$this->db->where('username', $userName);
$this-db->from('accounts');
$query = $this->db->get();
if ($query->num_rows() > 0) {
return true;
}
return false;
}
This my code which I used in one of my projects replace the words with your code:
$this->form_validation->set_rules('companyname','Company Name','trim|required|callback_companyname_exist');
Here is above callback function:
function companyname_exist($str) {
$this->db->where('company_name', $str);
$this->db->where('user_type','Shop');
$prod = $this->db->get('grs_user');
if ($prod->row()) {
$this->form_validation->set_message('companyname_exist', 'This Company name is already Available.');
return FALSE;
} else
return TRUE;
}
You can used this for already register email check also.
I have a problem in my web app, I use codeigniter 2.2.6, the app work app work fine when i run in localhost but when i was upload to web hosting, cannot set session user_data. Any one can help and discuss my problem? Thanks
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Login extends CI_Controller {
function __construct(){
parent::__construct();
$this->load->helper('form');
$this->load->library('form_validation');
$this->load->library('session');
}
public function index(){
if ($this->session->userdata('site_lang')=="") {
$this->session->set_userdata('site_lang','english');
}
$this->form_validation->set_rules('username_login', 'Username', 'required');
$this->form_validation->set_rules('password_login', 'Password', 'required');
if ($this->form_validation->run()){
//my code !
$m_url = URL_API;
$function = "login_user";
$username_login = $this->input->post('username_login');
$password_login = $this->input->post('password_login');
$url = $m_url . "/" . $function . "?" ."u=". $username_login . "&" ."p=". md5($password_login);
$json_data = file_get_contents($url);
$data = json_decode($json_data);
$status = $data->status;
if ($data->status == "000"){
$login= array (
'session_username_login' => $data->username,
'session_customer_id' => $data->customer_id,
'session_customer_no' => $data->customer_no,
'session_customer_name' => $data->customer_name,
'session_customer_email' => $data->customer_email,
'session_customer_gender' => $data->customer_gender,
'session_customer_status' => $data->customer_status,
'session_customer_handphone' => $data->customer_handphone,
'session_customer_birthday' => $data->customer_birthday,
'session_customer_address' => $data->customer_address,
'session_password_login' => md5($password_login) );
$this->session->set_userdata($login);
$_SESSION['session_username_login'] = $data->username;
}
elseif ($status == "007") {
$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">'.lang('username_password_wrong').'</div>');
redirect(MENU_LOGIN);
}
elseif ($status == "005") {
$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">'.lang('password_wrong').'</div>');
redirect(MENU_LOGIN);
}
elseif ($status == "004") {
$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">'.lang('username_wrong').'</div>');
redirect(MENU_LOGIN);
}
}
if($this->session->userdata('session_password_login') != null){
redirect(MENU_MARKETPLACE);
exit;
}
}
$this->load->view(MENU_LOGIN);
}
}
I am new at codeigniter and I got a question. I have a form with validation and that works fine, but say if I enter data in a field and leave the rest blank, the validation will show me the errors and clear the data that has been entered....how do I fix this?
Here is my controller code:
function submitclub()
{
$this->form_validation->set_rules('lastname', 'Last Name', 'required');
$this->form_validation->set_rules('firstname', 'First Name', 'required');
if ($this->form_validation->run() == FALSE)
{
$dataclub['clubname'] = $this->club_model->get(0, FALSE);
$dataclub['division'] = $this->division_model->get(0, FALSE);
$data['reset'] = TRUE;
$view = 'individual/individual_view';
}
Any help would be much apperciated
Solved this by doing this in my view:
<?php echo form_input('lastname', set_value('lastname'), 'id=lastname'); ?>
<?php echo form_error('lastname'); ?>
I have been dealing with a problem for a while. How can I set the validation errors using redirect in a function? This is the code I have in my controller :
function send()
{
$this->form_validation->set_rules('e-mail', 'Email', 'trim|required|valid_email');
$this->form_validation->set_rules('cellphone', 'Cellphone Number', 'trim|required|is_natural');
$this->form_validation->set_message('required', '%s is required.');
$this->form_validation->set_message('valid_email', '%s is not a valid Email Address');
$this->form_validation->set_message('is_natural', '%s can only contain numbers.');
$this->form_validation->set_error_delimiters('<li>', '</li>');
if($this->form_validation->run() == FALSE)
{
redirect ('/');
}
else
{
echo '<pre>';
print_r($_POST);
echo '<pre>';
}
}
And this is the code I use in my view file:
<? if (validation_errors())
{
echo '<div id="validation_errors" title="Error:">';
echo '<div class="response-msgs errors ui-corner-all"><span>Errors:</span><br /><ul>';
echo validation_errors();
echo '</ul></div>';
echo '</div>';
}
?>
I found the way to do it. Redirecting does not keep the data to be shown. I used the code below to solve the problem:
if($this->form_validation->run() == FALSE)
{
$this->index();
}
I know it's a bit late but this method works wonders for me.
If you are validating your form in a different function than the one the form is loaded in, you can send your validation_errors() to any page that you redirect() by passing the validation_errors() method to $this->session->set_flashdata() like so:
if ($this->form_validation->run() == FALSE) {
$this->session->set_flashdata('error', validation_errors());
redirect('/');
}
In your controller functions where you would like your errors or messages to be received you can then set them to the $data array like so:
if (!empty($this->session->flashdata('message'))) {
$data['message'] = $this->session->flashdata('message');
} elseif (!empty($this->session->flashdata('error'))) {
$data['error'] = $this->session->flashdata('error');
}
At the top of my views I usually include:
<?php if (isset($message)) {
echo '<p class="alert alert-info">'.$message.'</p>';
} elseif (isset($error)) {
echo '<p class="alert alert-danger"><strong>Error: </strong>'.$error.'</p>';
}?>
Using twitter bootstrap classes to format the messages helps to differentiate them.
I included the message flashdata so that you can see how whatever type of message or error you want to send, you are able to format them differently for all information, warning, success and error messages.
As per my comment:
function index()
{
$this->load->library('form_validation');
$data = array
(
'Param' => 'Value'
);
if($this->input->post('cellphone', true) !== false)
{
if($this->form_validation->run() != FALSE)
{
echo '<pre>' . print_r($_POST, true) . '</pre>';
}
}
$this->load->view('index', $data);
}
First, you need to change your form so it points to the current page, i.e. current_url() or site_url('controller/index').
When you go to the index without posting, it will simply skip the validation. Upon submitting your form, it will run the validation.
You can then use the built in form_error or validation_errors methods to display the errors within your index view.
finally i got a solution for the redirect with validation_errors
This is using to pass the validation_errors in the session data,
i do it like this
if ($this->form_validation->run()) {
$data = array(
'email' => $this->input->post('email'),
'is_login' => true
);
$this->session->set_userdata($data);
redirect($this->input->post('redirect'));
}
else
{
$data = array (
'errors' => validation_errors(),
'is_login' => false
);
$this->session->set_userdata($data);
redirect($this->input->post('redirect'));
}
and in the page i used
$this->session->set_flashdata('redirectToCurrent', current_url());
if ($this->session->userdata('is_login'))
{
echo "You are using this as : </br>" . $this->session->userdata('email');
echo "</br><a href='/logout'>Logout</a>";
}
else
{
echo form_open('login');
echo "" . $this->session->userdata('errors');
echo "email : " . form_input('email');
echo "Password : " . form_password('password');
echo form_submit('submit', 'Login');
echo form_hidden('redirect',$this->uri->uri_string());
echo form_close();
}
I wish you like this fast solution