how to update values in codeigniter rest for web service - php

hi all am using the following code
function update_profile_post() {
$serviceName = 'update_profile';
//getting posted values
$ip['user_id'] = trim($this->input->post('user_id'));
$ip['firstname'] = trim($this->input->post('firstname'));
$ip['lastname'] = trim($this->input->post('lastname'));
$ip['city'] = trim($this->input->post('city'));
$ip['state'] = trim($this->input->post('state'));
$ip['address'] = trim($this->input->post('address'));
$ip['phone_number'] = trim($this->input->post('phone_number'));
$ip['is_pic_changed'] = trim($this->input->post('is_pic_changed'));
$ipJson = json_encode($ip);
//validation
$ip_array[] = array("user_id", $ip['user_id'], "not_null", "user_id", "User ID is empty.");
$ip_array[] = array("firstname", $ip['firstname'], "not_null", "Firstname", "Firstname is empty.");
$ip_array[] = array("lastname", $ip['lastname'], "not_null", "lastname", "Lastname is empty.");
$ip_array[] = array("city", $ip['city'], "not_null", "city", "City is empty.");
$ip_array[] = array("state", $ip['state'], "not_null", "state", "State is empty.");
$validation_array = $this->validator->validate($ip_array);
print_r ($validation_array);
if ($validation_array !=1) {
$data['message'] = $validation_array;
$retVals = $this->clamo_lib->return_status('error', $serviceName, $data, $ipJson);
}
if ($ip['is_pic_changed'] == '1') {
$this->load->library('uploader');
$uploadPhoto = $this->uploader->upload_image($_FILES['profile_pic'], $ip);
if ($uploadPhoto == 'failed') {
$data['message'] = 'Upload failed. Please try again';
$retVals = $this->clamo_lib->return_status('error', $serviceName, $data, $ipJson);
} else {
$retVals = $this->user_model->user_update_profile_pic($ip, $uploadPhoto,$serviceName);
}
}
else{
$retVals = $this->user_model->user_update_profile($ip, $serviceName);
}
header("content-type: application/json");
echo $retVals;
exit;
}
model
function user_update_profile($input, $serviceName){
$ipJson = json_encode($input);
$updateArray = array(
'user_id' => $input['user_id'],
'firstname' => $input['firstname'],
'lastname' => $input['lastname'],
'address' => $input['address'],
'city' => $input['city'],
'state' => $input['state'],
'phone_number' => $input['phone_number'],
'user_modified_date' => date('Y-m-d H:i:s'),
);
$this->db->where('user_id', $input['user_id']);
$update = $this->db->update('users', $updateArray);
if ($update) {
$data['message'] = 'User profile updated Successfully.';
$status = $this->clamo_lib->return_status('success', $serviceName, $data, $ipJson);
} else {
$data['message'] = 'Error In Updating user profile';
$status = $this->clamo_lib->return_status('error', $serviceName, $data, $ipJson);
}
return $status;
}
here the issue is it is directly giving message updated successfully but when we are checking in db it is having all values as null what was the reason for what was wrong am doing. thanks

Related

login api with email, password or mobile number,password in codeigniter

I am trying to create an api which enables login for email id and password or mobile number and password in codeigniter but i was unable to do both i don't know the error. Here is my code of controller
Controller code
public function signin()
{
$this->default_file();
$responseData = array();
if(!empty($_POST['username']))
{
$userData = array();
$get_number = $this->validate_mobile($_POST['username']);
if(!empty($get_number))
{
$userData['usermob'] = $_POST['username'];
}
else
{
$userData['useremail'] = $_POST['username'];
}
$userData['userpass'] = $_POST['userpass'];
$userSignIn = $this->apm->signin($userData);
if((((!empty($userSignIn['id'])) && (!empty($userSignIn['useremail']))) ||((!empty($userSignIn['id'])) && (!empty($userSignIn['usermob'])))))
{
$session_data = array('id'=> $userSignIn['id'], 'logged_in'=> true);
$this->session->set_userdata('userLoggedIn', $session_data);
$userDetails = array();
$userDetails['id'] = $userSignIn['id'];
$getUserDetails = $this->apm->getUserDetails($userDetails);
$responseData['id'] = $getUserDetails['result']['u_id'];
$responseData['username'] = $getUserDetails['result']['username'];
$responseData['useremail'] = $getUserDetails['result']['useremail'];
$responseData['usermob'] = $getUserDetails['result']['usermob'];
$responseData['userlocation'] = $getUserDetails['result']['userlocation'];
$responseData['device_token'] = $getUserDetails['result']['device_token'];
$responseData['device_name'] = $getUserDetails['result']['device_name'];
$responseArray = array(
'apiName' => 'signin',
'version' => '1.0.0',
'responseCode' => 200,
'responseMessage' => 'logged in successfully',
'responseData' => $responseData
);
}
else
{
$responseArray = array(
'apiName' => 'signin',
'version' => '1.0.0',
'responseCode' => 204,
'responseMessage' => "Email or Passwor is incorrect.",
'responseData' => null//$responseData
);
}
}
else
{
$responseArray = array(
'apiName' => 'signin',
'version' => '1.0.0',
'responseCode' => 204,
'responseMessage' => "Sorry, please provide your input details.",
'responseData' => null//$responseData
);
}
echo json_encode($responseArray);
die();
}
My modal Code is here
public function signin($userData)
{
$arrData = array();
if(!empty($userData['useremail']) || !empty($userData['usermob']))
{
if(!empty($userData['useremail']))
{
$where = "useremail='".$userData['useremail']."'";
}
if(!empty($userData['usermob']))
{
$where = "usermob='".$userData['usermob']."'";
}
$this->db->select('*');
$this->db->from('users');
$this->db->where($where);
$result = $this->db->get()->result_array();
if(!empty($result))
{
if(!empty($userData['useremail']))
{
if(($userData['useremail']) && ($userData['userpass']))
{
$where = "useremail='".$userData['useremail']."' AND userpass='".$userData['userpass']."'";
$this->db->select('*');
$this->db->from('users');
$this->db->where($where);
$res = $this->db->get()->result_array();
if(!empty($res))
{
$arrData['id'] = $res[0]['u_id'];
$arrData['useremail'] = $res[0]['useremail'];
}
else
{
$arrData['errorLogin'] = 'Incorrect email or password';
}
}
}
if(!empty($userData['usermob']))
{
if(($userData['usermob']) && ($userData['userpass']))
{
$where = "usermob='".$userData['usermob']."' AND userpass='".$userData['userpass']."'";
$this->db->select('*');
$this->db->from('users');
$this->db->where($where);
$res = $this->db->get()->result_array();
if(!empty($res))
{
$arrData['id'] = $res[0]['u_id'];
$arrData['usermob'] = $res[0]['usermob'];
}
else
{
$arrData['errorLogin'] = 'Incorrect email or password';
}
}
}
}
else
{
$arrData['error'] = 'Please Enter username and password';
}
}
return $arrData;
}
I was trying to login with email and mobile number but my code gives only one access either with email or with mobile. i want help so that i can login with email and mobile number both.
I have tested this code using Postman, hope it can help:
public function signin($userData)
{
//get the data using useremail and userpass
$this->db->where('useremail', $userData['useremail']);
$this->db->where('userpass', $userData['userpass']);
$result = $this->db->get('users')->result_array();
//if there's no result, get the data using usermob and userpass
if (!$result) {
$this->db->where('usermob', $userData['usermob']);
$this->db->where('userpass', $userData['userpass']);
$result = $this->db->get('users')->result_array();
}
//if there's still no result, the username or password was incorect
if (!$result) {
$result = 'Wrong Username or Password';
}
return $result;
}

PHP MySQL - Validate email in PHP

currently I do a checking function to know email already exist or not in db. If exist then error, if not update data. But if existing user edit their data such as weight. Then it will give error because it detect email already exist. But the user only edit the weight data, not the email. can anyone help me how to solve this problem or have any recommendation to do this part. I'm using a CodeIgniter framework.
This is my controller
if (!empty($this->input->post()))
{
$data["weight"] = $this->input->post("weight");
$data["height"] = $this->input->post("height");
$data["username"] = $this->input->post("username");
$data["email"] = $this->input->post("email");
if (strlen($this->input->post("username")) < 6)
{
$result = $this->Global_model->GenerateOutputMsgArray("0", "Username should be at least 6 alphanumerics, please try again.");
}
elseif (!$this->Profile_model->ValidateEmail($this->input->post()))
{
$result = $this->Global_model->GenerateOutputMsgArray("0", "Email has been taken, please try another.");
} else {
$result["status"] == "1";
$this->Profile_model->UpdateProfile($data["weight"], $data["height"], $data["username"], $data["email"]);
$result = $this->Global_model->GenerateOutputMsgArray("1", "Your profile has been updated.", $data);
}
this is my model (validate email function and update data)
public function ValidateEmail($post)
{
$stat = "0";
$msg = "";
$data = array();
$output = array();
$query = $this->db->get_where("user", array("email" => $post["email"]));
$result = $query->row();
$result = (array)($result);
return ($result) ? false : true;
}
function UpdateProfile($weight, $height,$username, $email)
{
$data= array(
"weight" => $weight,
"height" => $height,
"username" => $username,
"email" => $email
);
$this->db->where("user_id", $this->session->userdata("user_id"));
$this->db->update("user", $data);
}
````````````````
You must be having user_id with email.
Try with this one.
public function ValidateEmail($post)
{
$stat = "0";
$msg = "";
$data = array();
$output = array();
$query = $this->db->get_where("user", array("email" => $post["email"]));
if($query->num_rows() > 0){
$result = $query->row();
if($result->user_id == $this->session->userdata("user_id")){
return false; // force doesn't exist
}else{
return true; // exists
}
}else{
return false; // as there is no row returned. it will return as doesn't exist
}
}

while posting data to web_service

i am trying to send data to web_service using this link.
http://localhost/FixItApp/admin.php?serial_number=mmm&items=asd&brand=qwe&price=sd&user_name=vfd
but data is not posting, can't figure_out why.
here is my web_service.
<?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "not set";
if(isset($_REQUEST))
{
$txt = serialize($_REQUEST);
}
fwrite($myfile, $txt);
fclose($myfile);
require_once "DatabaseConnection.php";
$result = null;
if ($_GET)
{
/* User table attribute */
$serial = filter_input(INPUT_GET, "serial_number", FILTER_SANITIZE_STRING);
$item = filter_input(INPUT_GET, "items", FILTER_SANITIZE_STRING);
$item_brand = filter_input(INPUT_GET, "brand", FILTER_SANITIZE_STRING);
$item_price = filter_input(INPUT_GET, "price", FILTER_SANITIZE_STRING);
$name = filter_input(INPUT_GET, "user_name", FILTER_SANITIZE_STRING);
if(is_null($serial))
{
echo "Null Values";
}
else
{
$select_ExistUser = #"SELECT serial_number from admin WHERE serial_number = '$serial'";
$resultUser = selectQuery($select_ExistUser);
if(count($resultUser)==0)
{
$query_one = "INSERT INTO admin(serial_number, items, brand, price, user_name)
VALUES('$serial', '$item', '$item_brand', $item_price, '$name')";
$result = insertQuery($query_one);
$insert_id = $db->insert_id;
if($insert_id)
{
echo "Great";
}
}
else
{
echo "ResultUser > 0";
}
}
}
if ($result)
{
$arr= [
"result" => $insert_id,
"status_message" => "Good",
"status_code" => 1
];
}
else
{
$arr = [
"result" => $result,
"status_message" => "Sorry!",
"status_code" => -1
];
}
echo json_encode($arr);

password_hash not updating when submit form

When I submit my form if password fields are submitted it should update the password else if empty does not update password.
I cannot seem to get the password_hash to update very strange. I can create new users fine with it but not update there password.
All other post are working fine update fine.
Not sure why password not updating? How am I able to fix issue thanks in advance.
<?php
class Model_user extends CI_Model {
public function edit_user($user_id, $data) {
$data = array(
'username' => $data['username'],
'user_group_id' => $data['user_group_id'],
'firstname' => $data['firstname'],
'lastname' => $data['lastname'],
'email' => $data['email'],
'image' => $data['image'],
'status' => $data['status']
);
$this->db->set($data);
$this->db->where('user_id', $user_id);
$this->db->update($this->db->dbprefix . 'user');
if ($data['password']) {
$options = [
'cost' => 11,
'salt' => mcrypt_create_iv(22, MCRYPT_DEV_URANDOM),
];
$data = array(
'password' => password_hash($_POST['password'], $options)
);
$this->db->set($data);
$this->db->where('user_id', $user_id);
$this->db->update($this->db->dbprefix . 'user');
}
}
}
Controller
<?php
class Users extends MY_Controller {
public function __construct() {
parent::__construct();
$this->load->model('admin/user/model_user');
}
public function index() {
$this->get_form();
}
public function update() {
$this->form_validation->set_rules('username', 'Username', 'required');
if ($this->form_validation->run($this) == FALSE) {
$this->get_form();
} else {
$this->model_user->edit_user($this->uri->segment(4), $_POST);
redirect('admin/user');
}
}
public function get_form() {
$data['title'] = "Users";
$data['breadcrumbs'] = array();
$data['breadcrumbs'][] = array(
'text' => 'Home',
'href' => site_url('admin/dashboard')
);
$data['breadcrumbs'][] = array(
'text' => "Users",
'href' => site_url('admin/user')
);
$user_info = $this->model_user->get_user($this->uri->segment(4));
if (isset($_POST['username'])) {
$data['username'] = $_POST['username'];
} elseif (!empty($user_info)) {
$data['username'] = $user_info['username'];
} else {
$data['username'] = '';
}
if (isset($_POST['user_group_id'])) {
$data['user_group_id'] = $_POST['user_group_id'];
} elseif (!empty($user_info)) {
$data['user_group_id'] = $user_info['user_group_id'];
} else {
$data['user_group_id'] = '';
}
$this->load->model('admin/user_group/user_group_model');
$data['user_groups'] = $this->user_group_model->get_user_groups();
if (isset($_POST['password'])) {
$data['password'] = $_POST['password'];
} else {
$data['password'] = '';
}
if (isset($_POST['confirm'])) {
$data['confirm'] = $_POST['confirm'];
} else {
$data['confirm'] = '';
}
if (isset($_POST['firstname'])) {
$data['firstname'] = $_POST['firstname'];
} elseif (!empty($user_info)) {
$data['firstname'] = $user_info['firstname'];
} else {
$data['firstname'] = '';
}
if (isset($_POST['lastname'])) {
$data['lastname'] = $_POST['lastname'];
} elseif (!empty($user_info)) {
$data['lastname'] = $user_info['lastname'];
} else {
$data['lastname'] = '';
}
if (isset($_POST['email'])) {
$data['email'] = $_POST['email'];
} elseif (!empty($user_info)) {
$data['email'] = $user_info['email'];
} else {
$data['email'] = '';
}
if (isset($_POST['image'])) {
$data['image'] = $_POST['image'];
} elseif (!empty($user_info)) {
$data['image'] = $user_info['image'];
} else {
$data['image'] = '';
}
$this->load->model('admin/tool/model_tool_image');
if (isset($_POST['image']) && is_file(FCPATH . 'image/catalog/' . $_POST['image'])) {
$data['thumb'] = $this->model_tool_image->resize($_POST['image'], 100, 100);
} elseif (!empty($user_info) && $user_info['image'] && is_file(FCPATH . 'image/catalog/' . $user_info['image'])) {
$data['thumb'] = $this->model_tool_image->resize($user_info['image'], 100, 100);
} else {
$data['thumb'] = $this->model_tool_image->resize('no_image.png', 100, 100);
}
$data['placeholder'] = $this->model_tool_image->resize('no_image.png', 100, 100);
if (isset($_POST['status'])) {
$data['status'] = $_POST['status'];
} elseif (!empty($user_info)) {
$data['status'] = $user_info['status'];
} else {
$data['status'] = 0;
}
$this->load->view('template/user/user_form_view', $data);
}
}
Take a closer look at the edit_user function. You receive $data but you immediately overwrite it. Please note that you don't set a password key to the newly created array. Then you check if ($data['password']) but that will never be true therefore the update will never be done.
There is a problem in your password_hash($_POST['password'], $options).
You passed $_POST['password'] instead of $data['password'].
It took me a while to figure it out I needed to create another variable out side of the if statement in my model like below and then was able to update if new password present.
All working now.
$input_password = $this->input->post('password');
if ($input_password) {
$password = password_hash($input_password, PASSWORD_BCRYPT);
$data_password = array(
'password' => $password
);
$this->db->where('user_id', $user_id);
$this->db->update($this->db->dbprefix . 'user', $data_password);
}

select and where condition in codeigniter

In this coding iam checking the whether email id is present in database.After that i need to change password.
function user_password($input, $serviceName){
$ipJson = json_encode($input);
$updateArray = array(
'email' => $input['email'],
'password' => md5($input['password']),
'user_modified_date' => date('Y-m-d H:i:s'),
);
$this->db->where('email', $input['email']);
$update = $this->db->update('users', $updateArray);
if ($update) {
$data['message'] = 'email id is present';
$status = $this->clamo_lib->return_status('success', $serviceName, $data, $ipJson);
}
else {
$data['message'] = 'Error In Updating Please Check Your Email ID';
$status = $this->clamo_lib->return_status('error', $serviceName, $data, $ipJson);
}
return $status;
}
if email is present in db i need to get "email id is present" message else i need to get "error"message.how i need to check the condition.
As you need to check that email address already in use or not.
So in model
$this->db->where("email",$input['email']);
$query = $this->db->get("users");
if($query->num_rows()>0){
$status['message'] = 'Email Already Exist';
}
function user_password($input, $serviceName)
{
$ipJson = json_encode($input);
$updateArray = array(
'email' => $input['email'],
'password' => md5($input['password']),
'user_modified_date' => date('Y-m-d H:i:s'),
);
$this->db->where('email', $input['email']);
$update = $this->db->update('users', $updateArray);
if ($update==TRUE)
{
$data['message'] = 'email id is present';
$status = $this->clamo_lib->return_status('success', $serviceName, $data, $ipJson);
}
else
{
$data['message'] = 'Error In Updating Please Check Your Email ID';
$status = $this->clamo_lib->return_status('error', $serviceName, $data, $ipJson);
}
return $status;
}
//change your update function in model something like this:
function update('users',$updatearray)
{
if(is_array($dataarray))
{
$this->db->trans_start();
$this->db->where('email',$this->input->post('email'));
$this->db->update('table',$updatearray);
$this->db->trans_complete();
return TRUE;
}
else
{
return FALSE
}
}

Categories