Codeigniter update function doesn't work corectly - codeigniter

I have a problem with the update function. This code is updating all rows in database and i want to update only the row with the login username.The "password" is one that i logged in and i want to replace with password3. The problem is that password replace all rows(passwords) in my database.
function edit_member()
{
$new_member_update_data = array(
'password' => md5($this->input->post('password3'))
);
$this->db->where('password',$this->input->post('password'));
$update = $this->db->update('memberships',$new_member_update_data);
return $update;
}

Suppose you have logged in,then you will get the userId from session right..?So use it here like
function edit_member()
{
$new_member_update_data = array(
'password' => md5($this->input->post('password3'))
);
$this->db->where('iUserId',$this->session->userdata('iUserId'));
$update = $this->db->update('memberships',$new_member_update_data);
return $update;
}
Consider that iUserId will be the field that is unique or even a auto increment field.

Check column password value and $this->input->post('password') value
function edit_member()
{
$password = md5($this->input->post('password3');
$this->db->set('password',$password );
$this->db->where('password',$this->input->post('password'));
$this->db->where('id',$this->input->post('id'));
$update = $this->db->update('memberships');
return $update;
}

Check your Password value which is in DB, if that is encrypted by MD5 then you have to pass the encrypted value of password in WHERE clause.
function edit_member()
{
$password = md5($this->input->post('password3');
$this->db->set('password',$password );
$this->db->where('password',md5($this->input->post('password'));
$update = $this->db->update('memberships');
return $update;
}

Related

CodeIgniter 3 code does not add data to database into 2 different tables (user_info & phone_info)

The problem is when I entered a new name no data is added. A similar thing happen when I entered an already existing name. Still, no data is added to the database. I am still new to CodeIgniter and not entirely sure my query builder inside the model is correct or not.
In the Model, I check if the name already exists insert data only into the phone_info table. IF name does not exist I insert data into user_info and phone_info.
Controller:
public function addData()
{
$name = $this->input->post('name');
$contact_num = $this->input->post('contact_num');
if($name == '') {
$result['message'] = "Please enter contact name";
} elseif($contact_num == '') {
$result['message'] = "Please enter contact number";
} else {
$result['message'] = "";
$data = array(
'name' => $name,
'contact_num' => $contact_num
);
$this->m->addData($data);
}
echo json_encode($result);
}
Model:
public function addData($data)
{
if(mysqli_num_rows($data['name']) > 0) {
$user = $this->db->get_where('user_info', array('name' => $data['name']))->result_array();
$user_id = $user['id'];
$phone_info = array(
'contact_num' => $data['contact_num'],
'user_id' => $user_id
);
$this->db->insert('phone_info',$phone_info);
} else {
$user_info = array(
'name' => $data['name']
);
$this->db->insert('user_info', $user_info);
$user = $this->db->get_where('user_info', array('name' => $data['name']))->result_array();
$user_id = $user['id'];
$phone_info = array(
'contact_num' => $data['contact_num'],
'user_id' => $user_id
);
$this->db->insert('phone_info', $phone_info);
}
}
DB-Table user_info:
DB-Table phone_info:
Extend and change your model to this:
public function findByTitle($name)
{
$this->db->where('name', $name);
return $this->result();
}
public function addData($data)
{
if(count($this->findByTitle($data['name'])) > 0) {
//.. your code
} else {
//.. your code
}
}
Explanation:
This:
if(mysqli_num_rows($data['name']) > 0)
..is not working to find database entries by name. To do this you can use codeigniters built in model functions and benefit from the MVC Pattern features, that CodeIgniter comes with.
I wrapped the actual findByName in a function so you can adapt this to other logic and use it elswehere later on. This function uses the query() method.
Read more about CodeIgniters Model Queries in the documentation.
Sidenote: mysqli_num_rows is used to iterate find results recieved by mysqli_query. This is very basic sql querying and you do not need that in a MVC-Framework like CodeIgniter. If you every appear to need write a manual sql-query, even then you should use CodeIgniters RawQuery methods.

change password when is set

i want to change password in my update method , when is $request->data['password'] is set and is not null
if is not set old password be replace
this is my code but i'm faced with error !
$user=Model::whereId($id)->update([
"updated_at" => Carbon::now(),
"department_id" => $department,
"username" => $request->data['username'],
'password'=>isset($request->data['password'])?bcrypt($request->data['password']):$user->password,
]);
You can use this solution
$data = [
"updated_at" => Carbon::now(),
"department_id" => $department,
"username" => $request->data['username'],
];
if (! empty($request->data['password'])) {
$data["password"] = bcrypt($request->data['password']);
}
$user = Model::whereId($id)->update($data);
isset checks if the password field exists in the request but if it exists there and is null then it will still pass through. Also your ternary is the other way around.
you can use empty for what you are trying to achieve like:
'password'=>!empty($request->data['password'])?bcrypt($request->data['password']):$user->password,
But if you want to use the ternary there then you must have retrieved your user model before that so your fallback actually has the value of the user password in the database. A similar approach is:
$user=Model::whereId($id)->first();
$user->updated_at = Carbon::now();
$user->department_id => $department;
$user->username = $request->data['username'];
if(!empty($request->data['password']){
$user->password=bcrypt($request->data['password']);
}
$user->save();
That way you don't need a fallback. Returning the user model with the latest changes you can use the fresh() function after you save()
return $user->fresh()
Use "dot" notation to access the arrays (like name="data['password']") :
$password = $request->input('data.password');
$model = Model::find($id);
$model->username = $request->input('data.username');
$model->department_id = $department;
if($password){
$model->password = Hash::make($password);
}
$model->save();
You may use the has method to determine if a value is present on the request. The has method returns true if the value is present on the request:
if ($request->has('data.password')) {
//
}
Or use whenHas. The whenHas method will execute the given closure if a value is present on the request:
$request->whenHas('data.password', function ($input) {
//
});

How To Get Auth ID form user table and grab it for store to other table on database

I want to get Auth ID from user who has logged in and then use the Auth ID to store on other table
User_detail Controller
this is my store function
$data = new ModelUser();
$user= new user();
$data->fill(Auth::user());
$data->id_user = Auth::get('id');
$data->jenis_kelamin = $request->jenis_kelamin;
$data->no_tlp = $request->no_tlp;
$data->jurusan = $request->jurusan;
$data->wilayah = $request->wilayah;
$data->save();
return redirect()->route('surveylist');
and this is function Login
public function LoginPost(Request $request)
{
$email = $request->email;
$password = $request->password;
$data = user::where('email',$email)->first();
if($data) //check email apakah ada atau tidak
{
if(Hash::check($password,$data->password))
{
Session::put('id',$data->id);
Session::put('full_name',$data->full_name);
Session::put('email',$data->email);
Session::put('login',TRUE);
return redirect('userdt');
}
else
{
return redirect('index')->with('alert','Password atau Email yang anda masukan salah !!! ' );
}
}
}
this is the routes files
Route::get('/index','UserController#show')->name('surevey.index');
Route::get('/logout','UserController#Logout')->name('user.logout');
Route::post('/registerpost','UserController#RegisterPost')->name('user.register');
Route::post('/loginpost','UserController#LoginPost')->name('user.login');
//reward routes
Route::get('/reward','RewardController#index')->name('reward.list');
//profile
Route::put('/editprofile/edit/{id}','UserController#edit')->name('profile.edit');
Route::post('/editprofile/update','UserController#update')->name('profile.update');
Route::get('/userdt',['middleware'=>'auth','uses'=>'UserController#userdetail'])->name('userdt.show');
Route::post('/userdt/store','UserController#store')->name('userdt.store');
//Survei
Route::get('/createsurvey','SurveyController#show')->name('survey.create');
Route::get('/surveylist','SurveyController#index')->name('survey.list');
Auth::routes();
ModelUser
protected $fillable = [
'id_user',
'jenis_kelamin',
'no_tlp',
'jurusan',
'wilayah'
];
protected $table ='user_detail';
public function user()
{
return $this->belongsTo(user::class);
}
and I get error like this
Argument 1 passed to Illuminate\Database\Eloquent\Model::fill() must
be of the type array, null given, called in
E:\Laravel\surevey\app\Http\Controllers\UserController.php on line 110
You don't need to use $data->fill(Auth::user()); as you have only single user_id field need to set.
Also you can get the current logged in user's id using. \Auth::user()->id
So your code would be as follow:
$data = new ModelUser();
$data->id_user = \Auth::user()->id;
$data->jenis_kelamin = $request->jenis_kelamin;
$data->no_tlp = $request->no_tlp;
$data->jurusan = $request->jurusan;
$data->wilayah = $request->wilayah;
$data->save();
return redirect()->route('surveylist');
Note: Make sure you have included auth middleware with your route.
Like:
Route::get('profile', ['middleware' => 'auth', function() {
// Only authenticated users may enter...
}]);
And you have followed the authuntication process carefully.
https://laravel.com/docs/5.2/authentication
Edited:
Your loging should be changed as:
public function LoginPost(Request $request)
{
$email = $request->email;
$password = $request->password;
if (Auth::attempt(['email' => $email, 'password' => $password])) {
// Authentication passed...
return redirect()->intended('userdt');
}
return redirect('index')->with('alert','Password atau Email yang anda masukan salah !!! ' );
}
If your reverse one-to-one relationship in the User Model looks like this:
public function detail()
{
return $this->hasOne(ModelUser::class);
}
And you are sure a user is logged in, you could simply do this
$data = Auth::user()->detail()->save($request->all());
return redirect()->route('surveylist');
Laravel's ORM takes care of the rest.
should be Auth::id() or Auth::user()->id but seems like your Auth::user() is returning a null.make sure you sessions, routes are set up properly.
use Auth::attempt()to login user

How to attach variable to reset password link view in laravel?

I am using laravel 5.2 where I need to sent an OTP code to reset password, though email is being sent with built in subject and limited message done by make:auth command but how to customize? I have tried to follow the link unfortunately I am unable to understand how i can use this to solve.
I customized the api like this
public function sendResetLinkEmail(Request $request)
{
$this->validateSendResetLinkEmail($request);
$broker = $this->getBroker();
$email = $request->input('email');
$userid = DB::table('users')->where('email','=',$email)->value('id');
$uniqueotp = "DIYA".uniqid();
$curr_timestamp = strtotime(date("Y-m-d H:i:s"));
$date = strtotime("+7 day", $curr_timestamp);
$expiry_otp = date('Y-m-d H:i:s',$date);
$ip_address = $request->ip();
DB::table('otp_users')->insert([
'user_id' => $userid,
'status' => 0,
'otp_code' => $uniqueotp,
'ipaddress'=>$ip_address,
'expires_at'=>$expiry_otp
]);
$response = Password::broker($broker)->sendResetLink(
$this->getSendResetLinkEmailCredentials($request),
$this->resetEmailBuilder()
);
switch ($response) {
case Password::RESET_LINK_SENT:
return $this->getSendResetLinkEmailSuccessResponse($request,$response);
case Password::INVALID_USER:
default:
return $this->getSendResetLinkEmailFailureResponse($response);
}
}
Any idea how I can achieve?
My required email message like this:
Hello, Tamaghna Banerjee Click here to reset your password:
Your OTP is: B16445512121
Reset Your Password through http://localhost/diya/public/password/reset/83baba9f61fc851b9d80b515415ec86c43b03b56b068e1888256db7a7831ba83?email=tamaghnabanerjee%40live.com

Hash::check() return false in laravel 5

I'm just starting with laravel 5, I'm doing a simple login function to check if email and password passed by user matches with the email and password stored in the database. I've been reading the documentation ([https://laravel.com/docs/5.0/hashing1) but Hash::check($content['password'], $user->{'password'}) returns false always. My code looks like this.
When I create a new user I hash the password like that:
$content = json_decode($request->getContent(), true);
$user -> password = Hash::make($content['email']);
And my login function looks like that:
public function login(Request $request)
{
$content = json_decode($request -> getContent(), true);
$user = DB::table('users')->where('email', $content['email'])->first();
if (Hash::check($content['password'], $user->{'password'}))
{
// Redirect to dashboard
}
}
Thanks in advance!!
Actually you are hashing the email instead of password while creating the user. change the code from
$user->password = Hash::make($content['email']);
To
$user->password = Hash::make($content['password']);
i came up with same issue. check database users table, password field. make the size of the field to 60 or more. this fixed mine.
The facade Hash just will encrypt your data:
Hash::make('123456');
is the same that:
$password = bcrypt('123456');
to login a user you need to use AuthController functions:
Auth::attempt(['email' => 'test#test.com' , 'password' => Hash::make('password')]);
it's a example.
If you're receiving a request, you can add this method to login:
if(Auth::attempt(['email' => $request->email, 'password' => $request->password , 'active' => 1])){
flash()->success('Successfully logged in!');
return redirect('/');
}
the attempt function will hash your password field and will compare with database data.

Resources