codeigniter array variable - php

Here is my code so far, it all works except when I try to make 'company' = $company there's something im missing, and id love to know what
if($query) // if the user's credentials validated///
{
$this->db->where('username');
$this->db->select('company');
$company = $this->db->get('user');
$data = array(
'username' => $this->input->post('username'),
'company' => $company
'is_logged_in' => true
);
$this->session->set_userdata($data);
redirect('site/members_area');
}
else
{
$this->index();
}

Both the other answers fix one of the two errors in your code, this is an addition.
if($query) {
$username = $this->input->post('username');
$this->db->select('company')->where('username', $username);
$result = $this->db->get('user')->row_array();
$data = array(
'username' => $username,
'company' => $row['company'],
'is_logged_in' => true
);
$this->session->set_userdata($data);
redirect('site/members_area');
} else {
$this->index();
}
See what I did there? You don't need to use result_array() then grab $query_result[0] as row_array() does that for you. And with a little method chaining thrown in for good measure you can clean up your syntax.

There is a missing comma after "$company".
EDIT: Based on the discussion in the comments, I've rewritten your code to (hopefully) get the value of the company:
if($query) {
$username = $this->input->post('username');
$this->db->where('username', $username);
$this->db->select('company');
$result = $this->db->get('user');
// Here we assume that the query succeeded.
// You should probably double-check.
$company = $result->result_array[0]['company'];
$data = array(
'username' => $username,
'company' => $company,
'is_logged_in' => true
);
$this->session->set_userdata($data);
redirect('site/members_area');
} else {
$this->index();
}

result_array is a function, not a variable. Try
if($query) {
$username = $this->input->post('username');
$this->db->where('username', $username);
$this->db->select('company');
$query_result = $this->db->get('user');
// Here we assume that the query succeeded.
// You should probably double-check.
$result= $query_result->result_array();
$data = array(
'username' => $username,
'company' => $result[0]['company'],
'is_logged_in' => true
);
$this->session->set_userdata($data);
redirect('site/members_area');
} else {
$this->index();
}

Related

how to get match only one username and password in array

$data = array(
array(
'username' => 'bharatbhai#gmail.com',
'password' => '12345'
),
array(
'username' => 'test#gmail.com',
'password' => '8520'
),
array(
'username' =>'abc#gmail.com',
'password' => '123123'
)
);
and my condition is here
my task is only match one username to one password
but i got error
$check_email = false;
if(array_search($email,array_column($data,'username')) !== FALSE){
$check_email = true;
}
$check_pass = false;
if(array_search($password,array_column($data,'password')) !== FALSE){
$check_pass = true;
}
if(!empty($check_email) && !empty($check_pass)){
echo "<h2>Email and Password matched</h2>";
}
else{
echo '<h2>Oh no email and password not matched.</h2>';
i am match my condition using array_column funcation.
You need to update your logic which checks if both username and password are same in each sub array. I made quick logic you should apply to your code.
<?php
$email = "bharatbhai#gmail.com";
$password = "12345";
$data = array(
array(
'username' => 'bharatbhai#gmail.com',
'password' => '12345'
),
array(
'username' => 'test#gmail.com',
'password' => '8520'
),
array(
'username' =>'abc#gmail.com',
'password' => '123123'
)
);
$hasSameMailAndPass = false;
foreach($data as $key => $value){
if($value["username"] == $email and $value["password"] == $password){
$hasSameMailAndPass = true;
}
}
if($hasSameMailAndPass){
echo "<h2>Email and Password matched</h2>";
} else {
echo '<h2>Oh no email and password not matched.</h2>';
}
?>
I think you can perform a multilevel conditional check.
Actually it seems you search the existancce of the email and of the password, but not actually for the same user.
Does this email exits? yes or no?
does this passwrod exists? yes or no?
Actually should be the following:
does this email exists? yesr or no?
if yes, does that email fit with this password? yes or no?
So you could check if a user exists and has right credentials
$data = array(
array(
'username' => 'bharatbhai#gmail.com',
'password' => '12345'
),
array(
'username' => 'test#gmail.com',
'password' => '8520'
),
array(
'username' =>'abc#gmail.com',
'password' => '123123'
)
);
/**
* #param array $login array('email'=> 'loginemail', 'password'=> 'loginpwd')
* #return bool
*/
function canBeAuthenticate(array $data, array $login)
{
$hasMail = false;
$userIndex = null;
# check if email exists in system
# if not, not even check pwd and return false
# if exites, get ID of user and then check pwd
foreach ($users as $index => $userData) {
if ( $userData == $login['email'] ) {
$hasMail = true;
$userIndex = $index;
}
}
if (!$hasMail) {
echo 'Email not in system';
return false;
}
if ($data[$userIndex]['password'] == $login['password']) {
echo 'Match';
return true;
}
echo 'wrong password';
return false;
}

How To Save auto increment id in another table using codeigniter

public function register() {
if (isset($_POST['register'])) {
$u = $_POST['uname'];
$this->load->database();
$this->load->database();
$this->db->select('uname');
$this->db->from('login');
$this->db->where(array('uname' => $u));
$query1 = $this->db->get();
if (!$query1->num_rows() == 1) {
$data = array(
'fname' => $_POST['fname'],
'lname' => $_POST['lname'],
'dob' => $_POST['dob'],
'gender' => $_POST['gender'],
'email' => $_POST['email']
);
$this->load->database();
$this->db->insert('user', $data);
$data1 = array(
//'User_idUser'=>$_POST[$query1],
'uname' => $_POST['uname'],
'upass' => $_POST['upass']
);
$this->db->insert('login', $data1);
} else {
$_SESSION["ex"] = "User All Ready Exists";
}
}
$this->load->view('register');
}
I want to get auto increment id of user table to save in login table as a foreign key to identify which user is currently logging. the code is running perfectly.
the user table is a parent table and
login table is a child table.
User following code to get ID of last insert operation.
$insert_id = $this->db->insert_id();
And use $inser_id to add it to any table you want.
So if I open the commented line of your code,
$data1 = array(
'User_idUser' => $insert_id, // Assuming that UseridUser is your columne to store the Autoincremented user id from previous insert query.
'uname' => $_POST['uname'],
'upass' => $_POST['upass']
);

Codeigniter form_validation->run() is returning false

I know this question has been asked here a ton of times and I have seen the answers, but none of them solves my problem.
I have two REST API's Controllers and in both of them, the form_validation always returns false. When I comment out the validation section, both my controllers work fine.
This is my code.
The first controller is used for registration.
class ApiController extends REST_Controller{
public function create_password($password){
return hash("sha256", $password);
}
public function data_post(){
$this->form_validation->set_rules(
'username','User Name','trim|required|min_length[5]|max_length[30]|is_unique[users.user_name]|xss_clean');
$this->form_validation->set_rules('firstname','First Name','trim|required|alpha|min_lenght[3]|max_length[30]|xss_clean');
$this->form_validation->set_rules('lastname','Last Name','trim|required|alpha|min_lenght[3]|max_length[30]|xss_clean');
$this->form_validation->set_rules('email','Email','trim|required|valid_email|is_unique[users.user_email]');
$this->form_validation->set_rules('password','Password','trim|required');
$this->form_validation->set_rules('cpassword','Confirm Password','trim|required|matches[password]');
$this->form_validation->set_rules('gender','Gender','required');
$this->form_validation->set_rules('dob','Date of Birth','required');
$this->form_validation->set_rules('phone','Mobile Number','required');
if($this->form_validation->run() === FALSE){
$errors = validation_errors();
$message = array(
'status' => FALSE,
'message' => $errors
);
//$this->response($message, REST_Controller::HTTP_NOT_ACCEPTABLE);
echo validation_errors();
return;
}
$userpass = $this->create_password($this->post('password'));
$data = array('user_name'=>$this->post('username'),
'first_name'=>$this->post('firstname'),
'last_name'=>$this->post('lastname'),
'user_email'=>$this->post('email'),
'password'=>$userpass,
'date_of_birth'=> $this->post('dob'),
'mobile_phone' => $this->post('phone'),
'user_gender' => $this->post('gender')
);
$recordEntered = $this->mainModel->insert($data);
$message = '';
if($recordEntered == 1){
$message = array(
'status' => TRUE,
'message' => 'Data Inserted Successfully'
);
}
$this->response($message, REST_Controller::HTTP_CREATED);
}
And this is the 2nd Controller, used for login
class Authentication extends REST_Controller{
function index_post(){
$this->form_validation->set_rules('username','User Name','trim|required|max_length[30]|xss_clean');
$this->form_validation->set_rules('password','Password','trim|required');
if($this->form_validation->run() === false){
$errors = validation_errors();
$message = array(
'status' => FALSE,
'message' => $errors
);
$this->response($message, REST_Controller::HTTP_NOT_ACCEPTABLE);
return;
}
$username = $this->post('username');
$password = $this->create_password($this->post('password'));
$message = '';
if($this->verify_user($username, $password)){
$data = array(
'email' => $this->post('username'),
'is_logged_in' => 1
);
$this->session->set_userdata($data);
$message = array(
'status' => TRUE,
'message' => 'Log In Successful'
);
$this->response($message, REST_Controller::HTTP_OK);
}
else{
$message = array(
'status' => FALSE,
'message' => 'Invalid Email/Username or Password'
);
$this->response($message, REST_Controller::HTTP_NOT_FOUND);
}
}
public function verify_user($username, $password){
if($this->mainModel->getUser($username, $password)){
return true;
}
else{
return false;
}
}
public function create_password($password){
return hash("sha256", $password);
}
}
I am relatively new to Codeigniter and I am under a deadline which expires today.
Any help would be greatly appreciated.
First Change :
Sometimes you may want to validate an array that does not originate from $_POST data.
In this case, you can specify the array to be validated:
$data = array(
'username' => 'johndoe',
'password' => 'mypassword',
'passconf' => 'mypassword'
);
$this->form_validation->set_data($data);
Creating validation rules, running the validation, and retrieving error messages works the same whether you are validating $_POST data or another array of your choice.
You have to call the set_data() method before defining any validation rules.
see this link :
https://www.codeigniter.com/user_guide/libraries/form_validation.html#validating-an-array-other-than-post
Second Change :
In ApiController controller
Please remove xss_clean from the set_rules. xss_clean is not a native rule
$this->form_validation->set_rules('username','User Name','trim|required|min_length[5]|max_length[30]|is_unique[users.user_name]');
$this->form_validation->set_rules('firstname','First Name','trim|required|alpha|min_lenght[3]|max_length[30]');
$this->form_validation->set_rules('lastname','Last Name','trim|required|alpha|min_lenght[3]|max_length[30]');
AND Also from
In Authentication controller
$this->form_validation->set_rules('username','User Name','trim|required|max_length[30]');
Please read this for the reference :
https://www.codeigniter.com/user_guide/libraries/form_validation.html#rule-reference
For security helper ( xss_clean )
https://www.codeigniter.com/user_guide/helpers/security_helper.html
removing the xss_clean makes my code works perfectly

How to set session userdata from database in codeigniter?

I have problem with my session login in codeigniter 3. I can't get data from database to insert session. Whats wrong with my code?
My Controller
function __construct(){
parent::__construct();
$this->load->model('m_login');
}
function index(){
$this->load->view('v_login');
}
function aksi_login(){
$username = $this->input->post('username');
$password = $this->input->post('password');
$where = array(
'username' => $username,
'password' => md5($password)
);
$cek = $this->m_login->cek_login("admin",$where)->num_rows();
if($cek > 0){
$data_session = array(
'username' => $cek['username'],
'nama' => $cek['nama']
'status' => "login"
);
$this->session->set_userdata($data_session);
redirect(base_url("admin"));
}else{
echo "Username dan password salah !";
}
}
}
My Model
<?php
class M_login extends CI_Model{
function cek_login($table,$where){
return $this->db->get_where($table,$where);
}
}
1.m_login->cek_login
this functions returns a SQL QUERY OBJECT
2.the SQL QUERY OBJECT ->num_rows() function returns a INT ($cek)
3.so $cek is a INT . so u cant use like an array ($cek['username'])
so Please try this code
function aksi_login(){
$username = $this->input->post('username');
$password = $this->input->post('password');
$where = array(
'username' => $username,
'password' => md5($password)
);
$cek = $this->m_login->cek_login("admin",$where);//$cek is a Query Object
$rows = $cek->num_rows();//$rows is a INT
if($rows > 0){
$cek = $cek->row_array();//now u get an Array
$data_session = array(
'username' => $cek['username'],
'nama' => $cek['nama']
'status' => "login"
);
$this->session->set_userdata($data_session);
redirect(base_url("admin"));
}else{
echo "Username dan password salah !";
}
}
Try This
if($cek > 0){
$cek = $cek->row_array();
$data_session = array(
'username' => $cek['username'],
'nama' => $cek['nama']
'status' => "login"
);
$this->session->set_userdata($data_session);
redirect(base_url("admin"));
}else{
echo "Username dan password salah !";
}
Try like this...
In codeigniter row_array() takes the first matched row in array format.So your function aksi_login() must be like this...
function aksi_login(){
$username = $this->input->post('username');
$password = $this->input->post('password');
$where = array(
'username' => $username,
'password' => md5($password)
);
$result = $this->m_login->cek_login("admin",$where);
$cek = $this->m_login->cek_login("admin",$where)->num_rows();
if($cek > 0){
$cek = $result->row_array();//no your records are in array format having matched row
$data_session = array(
'username' => $cek['username'],
'nama' => $cek['nama']
'status' => "login"
);
$this->session->set_userdata($data_session);
redirect(base_url("admin"));
}else{
echo "Username dan password salah !";
}
}
For more refer here..https://www.codeigniter.com/userguide3/database/results.html

How to Session variable pass one controller to another controller using codeigniter

I have Two Controller.
1.Login Controller
2. NewsLine Controller
Login Controller Below Code:
$query = $this->login_model->select_login($_POST);
if ($query) {
$user = array(
'uname' => $query['uname'],
'pwd' => $query['pwd']
);
$this->session->set_userdata($user);
$_SESSION['id'] = $user['id'];
redirect('Newsline');
}
My Question is How To $_SESSION['id] pass to Newsline Controller
As mentioned in CodeIgniter documentation to set the session data you an do following,
$newdata = array(
'username' => 'uname',
'email' => 'uname#some-site.com'
);
$this->session->set_userdata($newdata);
Now this is how you an retrive the data,
$session_id = $this->session->userdata('email');
In your case your code should look like this,
if ($query) {
$user = array(
'uname' => $query['uname'],
'pwd' => $query['pwd'],
'id' => $query['id']
);
$this->session->set_userdata($user);
redirect('Newsline');
}
To retrive ID on NewsLine controller,
$session_id = $this->session->userdata('id');

Categories