I have a scenario where i have 2 tables i.e users and request and i am asking the user to fill a form, in which along with other data he has to fill email also. Now i want that if the user enters an email it should simply add the data in users table and pick the last insert id and then go ahead and save the data+last inserted id in request table and display the message
Your account is created..
Till here i have done the coding, but the part where i am stuck is
I want that if the user enters an email that is already present in users table then the code should pick the id that is present against that email and store it along with form data in the request table and display the message
"Request is submitted but you already have an account, please login to
check furthur details "
users table
id name email
1 sam sam#gmail.com
2 demo_user demo#gmail.com
request table
id email userid
1 demo#gmail 2
Controller
public function submit()
{
$this->form_validation->set_rules('email','Email','trim|required');
if($this->form_validation->run() == FALSE)
{
$erdata = array
(
'error' => validation_errors()
);
$this->session->set_flashdata($erdata);
redirect('home/index');
}
else
{
if($this->user_model->instant_submit())
{
$this->session->set_flashdata('msg','Your account is created');
}
else
{
echo "failed";
}
redirect('home/index');
}
}
Model
public function instant_submit()
{
$userdata = array(
'email' => $this->input->post('email')
);
$insert_data = $this->db->insert('users', $userdata);
$lastid = $this->db->insert_id();
$reqdata = array(
'email' => $this->input->post('email'),
'userid' => $lastid,
'status'=>'pending'
);
$insert_request = $this->db->insert('request', $reqdata);
return $insert_data;
}
View
<?php if($this->session->flashdata('msg')): ?>
<?php echo $this->session->flashdata('msg'); ?>
<?php endif; ?>
<?php
$reg_attributes = array('id'=>'form','role'=>"form");
echo form_open('home/submit', $reg_attributes);
?>
<?php
$data = array(
'type'=>'text',
'name'=>'email',
'placeholder'=>'Email',
'class'=>'form-control',
'id'=>'form-email'
);
echo form_input($data);
?>
<?php
$data = array(
'type'=>'submit',
'class'=>'btn-primary',
'name'=>'submit',
'content'=>'Submit!'
);
echo form_button($data);
?>
<?php echo form_close(); ?>
is_unique Returns FALSE if the form element is not unique to the table and field name in the parameter.
Syntax :
is_unique[table.field]
Example :
$this->form_validation->set_rules('email', 'Email', 'required|valid_email|is_unique[users.email]');
This will solve your problem
In your controller before you call this $this->user_model->instant_submit() add one more condition to check if email id already exist or not like below.
Controller
public function submit()
{
$this->form_validation->set_rules('email','Email','trim|required');
if($this->form_validation->run() == FALSE)
{
$erdata = array
(
'error' => validation_errors()
);
$this->session->set_flashdata($erdata);
redirect('home/index');
}
else
{
if(!$this->user_model->check_user_exist($this->input->post('email'))) {
if($this->user_model->instant_submit())
{
$this->session->set_flashdata('msg','Your account is created');
}
else
{
echo "failed";
}
} else {
//do whatever operation you want to do if user is already exist;
$this->session->set_flashdata('msg','Request is submitted but you already have an account, please login to check furthur details ');
}
redirect('home/index');
}
}
Now in your model create a function which can check the data of user
public function check_user_exist($email_id) {
$this->db->select('id');
$this->db->where('email',$email_id);
$query = $this->db->get('users');
$data = $query->row();
if($query->num_rows() == 1) {
return $data->id;
} else {
return false;
}
}
Note : Remember it will send false if user not found so it will create a new entry of that user.
Related
Check For Duplicate on Edit Function
Currently my DB table
USERDB
userId userName userPassword userEmail userAddress userPhone
What I want
Allow to check on "userName" duplication" and if "userName" return
true , then it allow to edit other textfield.
Problem Met:
When i did not change anything on my "userName" field , and i edited
userEmail, it will always return FALSE due to my "userName" is
duplicate with current DB data.
$checkvalidation = $this->userdb->UsernameDuplicatechecking($userName);
if($checkvalidation == TRUE){
$this->userdb->updateUser($userName,$userEmail,$userAddress,$userPhone,$id);
}else{
$this->session->set_flashdata('errormessage', 'Duplicate');
redirect("User/EditUserAccount/$id");
}
Update Model Code
public function updateUser($userName,$userEmail,$userAddress,$userPhone,$id);
{
$UserArray = array(
'userName' => $userName,
'userEmail' => $userEmail,
'userAddress' => $userAddress,
'userPhone' => $userPhone,
);
$this->db->set($UserArray);
$this->db->where('userId',$id);
$this->db->update('USERDB');
}
Will you please share the code of function UsernameDuplicatechecking($userName) or you can try the below solution and let me know if it helps. Add below function to your userdb model
function checkDuplicateUsername($userName)
{
$this->db->where('userName',$userName);
$query = $this->db->get('USERDB');
if ($query->num_rows() > 0){
return true;
}
else{
return false;
}
}
Now update your controller function as below:
$checkvalidation = $this->userdb->checkDuplicateUsername($userName);
if($checkvalidation == true){
$this->userdb->updateUser($userName,$userEmail,$userAddress,$userPhone,$id);
}else{
$this->session->set_flashdata('errormessage', 'Your message here');
redirect("User/EditUserAccount/$id");
}
Consider you have the username input named userName, one solution is you could add a conditional is_unique validation, so that if user doesn't change his/her username then don't validate it as unique.
This could be done by pulling user's userName from database by id and compare it with the posted userName value :
$id = $this->input->post('id');
$old_username = $this->db->get_where('USERDB', array('userId' => $id))->row_array();
$original_value = $old_username['userName'];
if($this->input->post('userName') != $original_value) {
$is_unique = '|is_unique[USERDB.userName]'
} else {
$is_unique = ''
}
$this->form_validation->set_rules('userName', 'User Name', 'required|trim|xss_clean'.$is_unique);
Instead of checking if ($query == true).Check if ($validation == true) and your else condition is wrong as if username is duplicate it will go in the if condition.
I am working on a Register and Login application with CodeIgniter 3 and Bootstrap.
In my "users" table I have an "active" column that can take either 0 or 1 as value.
I want to be able to change the value of the "active" column corresponding to a user from 0 to 1 (activate the user) by clicking a link in my users view:
The "Activate" button code in the users view:
<span class="glyphicon glyphicon-ok"></span> Enable
Still in the users view every table row has the id of the user:
<tr id="<?php echo $user->id ?>">
In my Usermodel model I have:
public function activateUser($user_id) {
$query = $this->db->get_where('users', ['id' => $user_id]);
return $query->row();
}
In my User controller I have:
public function activate($user_id) {
$this->load->model('Usermodel');
$user = $this->Usermodel->activateUser($user_id);
if ($user->active == 0) {
echo 'activate user';
} else {
echo 'user already active';
}
}
The url users/activate/1 returns "user already active" , while users/activate/2 returns "activate user", as expected. Being new to Codeigniter, I have tried numerous versions of the code above that resulted in errors:
public function activateUser($user_id) {
$query = $this->db->get_where('users', ['id' => $user_id])->update('users', $data);
return $query->row();
}
is one of those versions resulting in errors.
Can you please tell me what shall I change in the code to make work as desired?
If I understand correctly, activateUser should update the database row for that user and then return all updated user information. You are trying to mash two queries together that should be separate. Just take it in two steps:
public function activateUser($user_id) {
$user = null;
$updateQuery = $this->db->where('id', $user_id)->update('users', ['active' => 1]);
if ($updateQuery !== false) {
$userQuery = $this->db->get_where('users', ['id' => $user_id]);
$user = $userQuery->row();
}
return $user;
}
I put in a little bit of error checking; if for instance the user id was not valid this will return null.
Based on that error checking, your controller code might look something like:
public function activate($user_id) {
$this->load->model('Usermodel');
$user = $this->Usermodel->activateUser($user_id);
// $user->active will always be 1 here, unless there was an error
if (is_null($user) {
echo 'error activating user - check user id';
} else {
// I was assuming you would want to do something with the user object,
// but if not, you can simply return a success message.
echo 'user is now active';
}
}
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;
}
Model
function Updateno($user,$data){
$this->db->where('username', $user);
$this->db->update('user', $data);
}
Controller
//user login function
function Ulogin(){
if($this->session->userdata('user'))
{
$data['user'] = $this->session->userdata('user');
$this->load->view("User/choosecategory",$data);
}
else
{
$data = array(
'username' =>$this->input->post('username'),
'password' =>$this->input->post('password'),
);
$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('User/login');
}
else
{
if($this->user_model->userlogin($data)==false)
{
$data['error'] = '<div class="alert alert-danger text-danger">Please Provide Valid Username/Password!</div>';
$this->load->view('User/login',$data);
}
else
{
$this->session->set_userdata('user',$data['username']);
$data['user'] = $this->session->userdata('user');
$counter = array(
'logged_in' =>'logged_in'+1
);
$this->user_model->Updateno($this->session->userdata('user'),$counter);
$this->load->view("User/choosecategory",$data);
}
}
}
}
I want whenever user login successfully my logged_in cloumn value increase by 1 but in this code the value of logged_in column always to 1,plz help me anyone here
the only thing you need to do here is to increment the value by 1
try the following piece of code
your model
function Updateno($user)
{
$this->db->where('username', $user);
$this->db->set("logged_in","logged_in+1",false);
$this->db->update('user');
}
and in your controller
$this->user_model->Updateno($this->session->userdata('user'));
What you want to do is this:
$value = explode("logged_in", $counter['logged_in']); //get the number of the counter
$counter['logged_in'] = 'logged_in' . ((int)$value[1] +1); //increase value by 1
This will get the current counter value from your string and increase it by 1
I made a demo to show how you can use it
DEMO: https://eval.in/773121
I'd like some help please. I have a post page that has the full post and below the post a small form for adding comments. The uri of the post page is: site/posts/1, so it is in posts controller, and the form action is form_open(site_url('comments/add/'.$post->post_id)).
This is my add() function inside comments controller:
public function add($post_id){
// if nothing posted redirect
if (!$this->input->post()) {
redirect(site_url());
}
// TODO: save comment in database
$result = $this->comment_model->add($post_id);
if ($result !== false) {
redirect('posts/'.$post_id);
}
// TODO:load the view if required
}
and this is the add() function inside the comment model
public function add($post_id){
$post_data = array(
'post_id' => $post_id,
'username' => $this->input->post('username'),
'email' => $this->input->post('email'),
'comment' => $this->input->post('comment')
);
if ($this->validate($post_data)) {
$this->db->insert('comments', $post_data);
if ($this->db->affected_rows()) {
return $this->db->insert_id();
}
return false;
} else {
return false;
}
}
What I'm trying to do is if the $result = $this->comment_model->add($post_id); fails the validation to display the validation errors in my post view, else insert the comment and redirect to the same post page (site/posts/1).
The problem is that when I hit submit the form action goes in the comments/add/1, as expected, but doesn't do any these above.
Any ideas how can I fix this??
EDIT
I did a small change to the code without the 'confusing' validate() function. Maybe this is more helpful.
Comment controller:
public function add($post_id){
// if nothing posted redirect
if (!$this->input->post()) {
redirect(site_url());
}
// TODO: save comment in database
$this->form_validation->set_rules($this->comment_model->rules);
if ($this->form_validation->run() == true) {
echo "Ok! TODO save the comment.";
// $this->comment_model->add($post_id);
// redirect('posts/'.$post_id);
} else {
echo "Validation Failed! TODO: show validation errors!";
}
// TODO:load the view if required
}
Comment model:
public function add($post_id){
$post_data = array(
'post_id' => $post_id,
'username' => $this->input->post('username'),
'email' => $this->input->post('email'),
'comment' => $this->input->post('comment')
);
$this->db->insert('comments', $post_data);
if ($this->db->affected_rows()) {
return $this->db->insert_id();
}
return false;
}
You need away of passing validation_errors() back to your Posts controller. At the minute, when you perform the redirect in your add function (when the validation fails), you loose the validation errors thrown.
I would consider using flashdata (http://ellislab.com/codeigniter/user-guide/libraries/sessions.html) to pass a success/error message from your Comments controller back to your Posts controller. Something similar to the below:
Comments Controller:
public function add($post_id) {
// if nothing posted redirect
if (!$this->input->post()) {
redirect(site_url());
}
// TODO: save comment in database
$this->form_validation->set_rules($this->comment_model->rules);
if ($this->form_validation->run() == true) {
// Store the success message in flash data
$this->session->set_flashdata('message', 'Ok! TODO save the comment.');
// Redirect back to posts page
redirect('posts/'.$post_id, 'refresh');
} else {
// Store the error message in flash data
$this->session->set_flashdata('message', validation_errors());
// Redirect back to posts page
redirect('posts/'.$post_id, 'refresh');
}
}
Posts Controller:
public function index($post_id) {
$this->data['message'] = $this->session->flashdata('message');
$this->load->view('posts', $this->data);
}
Posts View:
echo $message;
Might not be perfect but hope it helps...