I am using code igniter, how can I give the output of my query to the function returnQuery? Then pass that value to my controller.
public function returnQuery() {
$sql = "SELECT USERCODE FROM tbl_users where USERNAME =? AND PASSWORD = ?";
$data = array(
'USERNAME' => $this->input->post('USERNAME'),
'PASSWORD' => $this->input->post('PASSWORD')
);
$query = $this->db->query($sql, $data);
}
You can return any function's value just like core PHP in CodeIgniter.
Modify line:
$query = $this->db->query($sql, $data);
To:
return $this->db->query($sql, $data);
Notice that I have removed $query assignment as it is not used anywhere.
We can return data without it.
After reading your comments you can return data as:
public function returnQuery()
{
$sql = "SELECT USERCODE FROM tbl_users where USERNAME =? AND PASSWORD = ?";
$data = array( 'USERNAME' => $this->input->post('USERNAME'), 'PASSWORD' => $this->input->post('PASSWORD') );
$query = $this->db->query($sql, $data);
$result = $query->result_array();
if(count($result) > 0){
return $result[0]["USERCODE"];
}
else{
return 0;
}
}
And now how can you use redirection:
//call function
$q = $this->login_model->returnQuery();
if ($q == 1){
redirect('login/adminIndex');
}
elseif ($q == 2) {
redirect('login/userIndex');
}
else{
redirect('login/restricted');
}
Note that in your code you are not comparing the values you are assigning
if ($q = 1) this should be if ($q == 1)
Related
i want to join the data of 2 tables in 1 table and display the data of 2 tables. I already have function that load the one table. can someone modify this function code to get the 2 tables ? im just a beginner in php.
Model_users.php
public function getUserGroup($userId = null)
{
if($userId) {
$sql = "SELECT * FROM user_group WHERE user_id = ?";
$query = $this->db->query($sql, array($userId));
$result = $query->row_array();
$group_id = $result['group_id'];
$g_sql = "SELECT * FROM groups WHERE id = ?";
$g_query = $this->db->query($g_sql, array($group_id));
$q_result = $g_query->row_array();
return $q_result;
}
}
Controller User.php
public function index()
{
if(!in_array('viewUser', $this->permission)) {
redirect('dashboard', 'refresh');
}
$user_data = $this->model_users->getUserData();
$result = array();
foreach ($user_data as $k => $v) {
$result[$k]['user_info'] = $v;
$group = $this->model_users->getUserGroup($v['id']);
$result[$k]['user_group'] = $group;
}
$this->data['user_data'] = $result;
$this->render_template('users/index', $this->data);
}
Here you go
$this->db->select("ug.*,g.*");
$this->db->from("user_group ug");
$this->db->join('groups g', 'ug.user_id = g.group_id');
$this->db->where("ug.user_id",1);
$query = $this->db->get();
if ($query->num_rows() > 0) {
$result = $query->result();
} else {
$result = null;
}
return $result;
I am new in PHP and trying to build one API which provide me json response of required data. There one table called user and I need email, username and user_type from it. I have coded like below for do it
$result = array();
$users = getOnlineUsers($conn);
$userinfo['email'] = $users['email'];
$userinfo['username'] = $users['username'];
$userinfo['user_type'] = $users['user_type'];
$result['status'] ="success";
$result['userData'] = $userinfo;
And function is like below
function getOnlineUsers($conn)
{
$q = $conn->prepare("SELECT * FROM table_users WHERE online_status = 1");
// $q->bind_param("s", $email);
$q->execute();
$result = $q->store_result();
$metaResults = $q->result_metadata();
$fields = $metaResults->fetch_fields();
$statementParams='';
foreach($fields as $field){
if(empty($statementParams)){
$statementParams.="\$column['".$field->name."']";
}else{
$statementParams.=", \$column['".$field->name."']";
}
}
$statment="\$q->bind_result($statementParams);";
eval($statment);
$q->fetch();
return $column;
}
Its working fine but giving me only one row in response. I want get all row instead of one. I am getting response like this
{"status":"success","userData":{"email":"abc#gmail.com","username":"rajrathodbvn","user_type":0}}
Let me know if someone can help me for solve my issue.
Thanks
That's a lot of code for something so simple. Select the columns you want:
function getOnlineUsers($conn) {
$q = $conn->prepare("SELECT email, username, user_type
FROM table_users
WHERE online_status = 1");
$q->execute();
return $q->fetchAll(PDO::FETCH_ASSOC);
}
Then assign:
$result['status'] = 'success';
$result['userData'] = getOnlineUsers($conn);
Or:
$result = ['status' => 'success', 'userData' => getOnlineUsers($conn)];
I am trying to set the company name in a session and retrieve the same to connect to a different database, i am setting the session using $this->session->set_userdata($newdata); and retrieving the session using $companyName = $this->session->userdata['newdata']['company']; but somehow retrieval is not happening and i am unable to load the correct db for updating logout information i.e it simply does not update the pr_system_attendance table by connecting to a different db. I am getting the correct value if i echo $company; after $company = $row1->company; this is FYI
My model code is as follows:
function check_admin_login(){
$this->db->where('username', trim($this->input->post('username')));
$this->db->where('userpass ', sha1(trim($this->input->post('userpass'))));
$this->db->where('status', '1');
$this->db->where('deleted', '0');
$this->db->select('*');
$query = $this->db->get($this->myTables['users']);
if($query->num_rows() > 0){
$row = $query->row();
$this->db->where('userid', $row->id);
$this->db->select('firstname,lastname,profileimage,company');
$query1 = $this->db->get($this->myTables['users_details']);
$row1 = $query1->row();
$newdata = array(
'is_admin_logged_in' => true,
'admin_user_name' => $row->username,
'admin_userpass' => $row->userpass,
'admin_id'=>$row->id,
'admin_lastlogin'=>date("d-m-Y H:i:s",$row->lastlogin),
'admin_lastloginip'=>$row->lastloginip,
'lastrefresh'=>time(),
'company'=>$row1->company
);
$company = $row1->company;
$this->session->set_userdata($newdata);
$companyName = $this->session->userdata['newdata']['company'];
$this->update_admin_login_time($this->session->userdata('admin_id'));
$this->admin_init_elements->set_global_user($row->username,$row->userpass);
if($this->input->post('remember'))
{
$cookie = array('name' => 'username','value' => $row->username,'expire' => time()+7600,'secure' => false);
$this->input->set_cookie($cookie);
}
$name = $row1->firstname.' '.$row1->lastname;
$cookie1 = array('name' => 'name','value' => $name,'expire' => time()+7600,'secure' => false);
$this->input->set_cookie($cookie1);
$cookie2 = array('name' => 'image','value' => $row1->profileimage,'expire' => time()+7600,'secure' => false);
$this->input->set_cookie($cookie2);
return 'Login Successful';
}else{
return 'Incorrect Username or Password.';
}
}
function logout()
{
global $USER;
$companyName = $this->session->userdata['newdata']['company'];
$otherdb = $this->load->database("$companyName", TRUE);
$this->db->from("$companyName"."pr_users");
$query1 = $this->db->query("Select * from pr_system_attendance where userid = '".$USER->id."' and DATE(`login_time`) = CURDATE()");
date_default_timezone_set('Asia/Calcutta');
if($query1->num_rows() > 0)
{
$row = $query1->row();
$sql1 = "UPDATE pr_system_attendance set logout_time = '".date('Y-m-d H:i:s')."' where userid = '".$USER->id."' and DATE(`login_time`) = CURDATE()";
$query2 = $this->db->query($sql1);
}
$sql="UPDATE `".$this->myTables['users']."` SET
`if_online` = '0'
WHERE `id` = '".$USER->id."'" ;
$query=$this->db->query($sql);
}
Get session data with below line of code
//$companyName = $this->session->userdata['newdata']['company'];
$companyName = $this->session->userdata('company');
I need select Name from databese where Email = $email;
if ($result) {
$Name = $this->db->select('Name');
$this->db->from('users');
$this->db->where('Email',$Email);
$sess_array = array(
'Name' => $Name
);
$this->session->set_userdata('logged_in',$sess_array);
print_r($sess_array);
}
You need to fetch Name from database then assign to your session
if ($result) {
$this->db->select('Name');
$this->db->from('users');
$this->db->where('Email',$Email);
$query=$this->db->get();
$result=$query->row(); // fetch single data Name
$sess_array = array(
'Name' => $result->Name // set Name to array
);
$this->session->set_userdata('logged_in',$sess_array);
}
Try this,
if ($result) {
$this->db->select('Name');
$query = $this->db->get_where('users',array('Email' => $Email));
$result = $query->row();
$sess_array = array(
'Name' => $result->Name
);
$this->session->set_userdata('logged_in',$sess_array);
print_r($sess_array);
}
also refer CodeIgniter Select Query
I'm currently trying to fetch two images location from my database, how do I return both columns and if both empty then echo another image. This is what I've got so far.
How do I return both photo and photo_small so that I may echo them in a php file.
PUBLIC FUNCTION Profile_Pic($uiD) {
$sth = $this->db->prepare("SELECT photo,photo_small FROM users WHERE uiD = :id");
$sth->execute(array(':id' => $uiD));
if ($sth->rowCount() > 0) {
$data = $row['photo'];
return $data;
} else {
$data = './icons/users.png';
return $data;
}
}
PUBLIC FUNCTION Profile_Pic($uiD) {
$sql = "SELECT photo,photo_small FROM users WHERE uiD = ?";
$sth = $this->db->prepare($sql);
$sth->execute(array($uiD));
$data = $sth->fetch();
if (empty($data['photo'])) {
$data['photo'] = './icons/users.png';
}
if (empty($data['photo_small'])) {
$data['photo_small'] = './icons/users.png';
}
return $data;
}
if you want to replace both images if even one is absent
PUBLIC FUNCTION Profile_Pic($uiD) {
$sql = "SELECT photo,photo_small FROM users WHERE uiD = ?";
$sth = $this->db->prepare($sql);
$sth->execute(array($uiD));
$data = $sth->fetch();
if (empty($data['photo']) || empty($data['photo_small'])) {
$data['photo'] = './icons/users.png';
$data['photo_small'] = './icons/users.png';
}
return $data;
}
Just return all of the values you want in an array.
You can ensure that both photo and photo_small are not empty strings or NULL by using empty().
Don't forget to retrieve your row using PDOStatement::fetch().
You should not use rowCount() to determine the number of rows returned in a SELECT statement. According to the documentation for PDOStatement::rowCount():
For most databases, PDOStatement::rowCount() does not return the number of rows affected by a SELECT statement.
Try this:
$row = $sth->fetch(PDO::FETCH_ASSOC);
if ($row && !empty($row['photo']) && !empty($row['photo_small'])) {
$data = array('photo' => $row['photo'], 'photo_small' => $row['photo_small']);
return $data;
} else {
$data = array('photo' => './icons/users.png', 'photo_small' => './icons/users.png');
return $data;
}
Then when you call the function, your returned result can be used like this:
$uiD = 1;
$result = Profile_Pic($uiD);
$photo = $result['photo'];
$photo_small = $result['photo_small'];