MySQL doesn't update properly - mysql

I am trying to update status for users. code works fine .but it can't update in DB
controller.php
public function update_customer(Request $request)
{
$sid = 1;
$setting['setting'] = Settings::editGeneral($sid);
$site_max_image_size = $setting['setting']->site_max_image_size;
$name = $request->input('name');
$username = $request->input('username');
$email = $request->input('email');
$user_type = $request->input('user_type');
$status =$request->input('status');
$data = array('name' => $name, 'username' => $username, 'email' => $email, 'user_type' => $user_type, 'password' => $pass, 'earnings' => $earnings, 'user_photo' => $user_image,'status'=>$status, 'updated_at' => date('Y-m-d H:i:s'));
Members::updateData($token, $data);
return redirect($page_url)->with('success', 'Update successfully.');
}
}
model.php
public static function updateData($token,$data){
DB::table('users')
->where('user_token', $token)
->update($data);
}
how to solve it??

You can use Model class instead of DB Facade. Like below:
User.php
protected $fillable = [
'name' , 'username' , 'email' , 'user_type' , 'password' , 'earnings' , 'user_photo' ,'status', 'updated_at'
];
public static function updateData($token,$data)
{
User::where('user_token', $token)
->update($data);
}

Related

Edit records CodeIgniter

I'm developing a basic crud application using PHP Codeigniter 3 with MySQL database.
I have done add and list method successfully but now I want to edit the record and have included an edit button in the records table in view. when I click on the button it will go to my edit record view but it shows some errors. I checked everything but I fail to resolve it.
This is my controller
<?php
class User extends CI_controller
{
public function index()
{
$this->load->model('User_model');
$users = $this->User_model->getUsers();
// print_r($users);
$data = array();
$data['users'] = $users;
$this->load->view('users/list',$data);
}
public function create()
{
//load model here
$this->load->model('User_model');
//load library
$this->load->library('form_validation');
$this->load->library('ckeditor');
$this->load->library('ckfinder');
//set rules
$this->form_validation->set_rules('name', 'Name', 'required');
$this->form_validation->set_rules('projectname', 'Projectname', 'required');
$this->form_validation->set_rules('projecttype', 'Projecttype', 'required');
$this->form_validation->set_rules('phone', 'Phone', 'required');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
$this->form_validation->set_rules('address', 'Address', 'required');
$this->form_validation->set_rules('projectdescription', 'Projectdescription', 'required');
// $this->form_validation->set_rules('termname', 'Termname', 'required');
// $this->form_validation->set_rules('termdescription', 'Termdescription', 'required');
$this->form_validation->set_rules('article_description', 'Article_description', 'required');
if ($this->form_validation->run() == true) {
// print_r($_POST);
// Array ( [name] => muhammad zawish [projectname] => test [projecttype] => Hardware [phone] => 03206270391 [email] => muhammadzawish#gmail.com [address] => Gondal Road, Sialkot, Punjab, Pakistan [projectdescription] => aaaaaaaaaa [termname] => aaaaaa [termdescription] => aaaaaaaa )
$name = $this->input->post('name');
$projectname = $this->input->post('projectname');
$projecttype = $this->input->post('projecttype');
$phone = $this->input->post('phone');
$email = $this->input->post('email');
$address = $this->input->post('address');
$projectdescription = $this->input->post('projectdescription');
// $termname = $this->input->post('termname');
// $termdescription = $this->input->post('termdescription');
$article_description = $this->input->post('article_description');
// $formData = array('name' => $name, 'projectname' => $projectname, 'projecttype' => $projecttype, 'phone' => $phone, 'email' => $email, 'address' => $address, 'projectdescription' => $projectdescription, 'termname' => $termname, 'termdescription' => $termdescription,);
$formData = array('name' => $name, 'projectname' => $projectname, 'projecttype' => $projecttype, 'phone' => $phone, 'email' => $email, 'address' => $address, 'projectdescription' => $projectdescription, 'article_description' => $article_description);
//ck editor files
$this->ckeditor->basePath = base_url() . 'asset/ckeditor/';
$this->ckeditor->config['toolbar'] = array(
array('Source', '-', 'Bold', 'Italic', 'Underline', '-', 'Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo', '-', 'NumberedList', 'BulletedList')
);
$this->ckeditor->config['language'] = 'it';
$this->ckeditor->config['width'] = '730px';
$this->ckeditor->config['height'] = '300px';
//Add Ckfinder to Ckeditor
$this->ckfinder->SetupCKEditor($this->ckeditor, '../../asset/ckfinder/');
$this->User_model->add_user($formData);
$this->session->set_flashdata('message', 'Record has been added successfully');
redirect(base_url('user/index'));
} else {
$this->load->view('users/create');
}
}
function edit($id){
$this->load->model('User_model');
$row = $this->User_model->getUser($id);
$data1 = array();
$data1['row'] = $row;
$this->load->view('users/edit', $data1);
}
}
this is my model
<?php
class User_model extends CI_Model{
public function add_user($formArray){
// $this->load->library('session');
$this->db->insert('users', $formArray);
}
//for view data fetch from database
public function getUsers(){
$users = $this->db->get('users')->result_array();
return $users;
}
//for edit record
function getUser($id){
$this->db->where('id', $id);
$row = $this->db->get('users')->row_array();
return $row;
}
}
?>
when I access my edit.php view
404 Page Not Found
The page you requested was not found.

ErrorException Creating default object from empty value in Laravel 6

when I'm trying to update user I got this error
this error point out at $user->first_name = $request->input('first_name');
update method
public function update($id, Request $request){
$this->validate($request, array(
'first_name' => 'string|max:255',
'last_name' => 'string|max:255',
'email' => "string|email|max:255|unique:users,email,$id",
'password' => "sometimes|nullable |string|min:8,$id",
'avatar' => 'image|mimes:jpg,jpeg,gif,png,svg|max:2048',
));
$password = bcrypt(request('password'));
$user = User::where('email',$request['email'])->first();
$user->first_name = $request->input('first_name');
$user->last_name = $request->input('last_name');
if(!empty($request->password))
{
$user->password = $password;
}
if($request->hasFile('avatar')){
$avatar = $request->file('avatar');
$filename = time() . '.' . $avatar->getClientOriginalExtension();
Image::make($avatar)->resize(300, 300)->save( public_path('/images/avatars/' . $filename ) );
$user->avatar = $filename;
}
$user->roles()->detach();
if ($request['user']) {
$user->roles()->attach(Role::where('name','User')->first());
}
if ($request['editor']) {
$user->roles()->attach(Role::where('name','Editor')->first());
}
if ($request['admin']) {
$user->roles()->attach(Role::where('name','Admin')->first());
}
$user->save();
return redirect('admin/users')->with('success', 'user is successfully saved');
}
Your assignment $user is null because there is no record with the email you are providing.
Use findOrFail($request['email']) so that you throw a ModelNotFoundException in this scenario.
OR
$user = User::where('email',$request['email'])->first();
if(!is_null($user) { // check not null of $user here
$user->first_name = $request->input('first_name');
$user->last_name = $request->input('last_name');
}
References:
https://laravel.com/docs/5.7/eloquent#retrieving-single-models
https://laracasts.com/discuss/channels/laravel/errorexception-in-profilecontrollerphp-line-98-creating-default-object-from-empty-value
You should use FindOrFail method instead
so instead of using this line:
$user = User::where('email',$request['email'])->first();
use this:
$user = User::findOrFail($id);
so FindOrFail will get the user by id and if it does not exist it will fail and show 404 Not found.

Laravel Slug Duplicate

when i trying to create post with the same slug it create post normally also in update the same problem
in this case i'v duplicate slugs for post
i search a lot about this problem but i didn't get any answers
any idea to solve this problem ?
Model
protected $fillable = [
'title', 'slug', 'body',
];
Controller
public function slug($string, $separator = '-') {
if (is_null($string)) {
return "";
}
$string = trim($string);
$string = mb_strtolower($string, "UTF-8");;
$string = preg_replace("/[^a-z0-9_\sءاأإآؤئبتثجحخدذرزسشصضطظعغفقكلمنهويةى]#u/", "", $string);
$string = preg_replace("/[\s-]+/", " ", $string);
$string = preg_replace("/[\s_]/", $separator, $string);
return $string;
}
public function store(Request $request)
{
$this->validate($request, array(
'title' => 'required|max:255',
'slug' => 'required|min:3|max:255|unique:posts',
'body' => 'required',
));
$post = new Post;
$post->title = $request->input('title');
$post->slug = $this->slug($request->slug);
$post->body = $request->input('body');
$post->save();
return redirect('admin/posts')->with('success', 'post is successfully saved');
}
public function update(Request $request, $id)
{
if ($request->isMethod('get'))
return view('content.admin.post.index', ['url' => Post::find($id)]);
else {
$rules = [
'title' => 'required|max:255',
'slug' => 'required|min:3|max:255|unique:posts,slug,{$post->slug},slug',
'body' => 'required',
];
$this->validate($request, $rules);
$post = Post::find($id);
$post->title = $request->title;
$post->slug = $this->slug($request->slug);
$post->body = $request->body;
$post->save();
return redirect('/admin/posts');
}
}
Preform your transformations on the slug field before passing it to the validator.
public function store(Request $request)
{
$request->slug = $this->slug($request->slug);
$this->validate($request, array(
'title' => 'required|max:255',
'slug' => 'required|min:3|max:255|unique:posts',
'body' => 'required',
));
$post = new Post;
$post->title = $request->input('title');
$post->slug = $request->input('slug');
$post->body = $request->input('body');
$post->save();
return redirect('admin/posts')->with('success', 'post is successfully saved');
}
Why not just set slug column as unique in database migration?
Like this:
$table->string('slug')->unique();

Inserting variables in Yii2 to Database

I am trying to insert $product, $pric and $user to database table cart. Following is the function that I have created in SiteController.php.
public function actionCartadd($id)
{
$product = Additem::find()
->select('product')
->where(['id' => $id])
->one();
$pric = Additem::find()
->select('price')
->where(['id' => $id])
->one();
$user = Yii::$app->user->identity->username;
$connection = Yii::$app->getDb();
$result = Yii::$app->db->createCommand()
->insert('cart', [
'product' => '$product',
'price' => '$pric',
'user' => '$user',
])->execute();
if ($result)
return $this->render('custstore');
}
However, this end up in error. Can anyone suggest any fix
Try this following code
$result = Yii::$app->db->createCommand()->insert('cart', [
'product' => $product->product,
'price' => $pric->price,
'user' => $user
])->execute();
Look at this fragment:
'product' => '$product',
'price' => '$pric',
'user' => '$user',
Use double quotes in values or just variables without quotes
Also, better way to fetch product and price:
$productItem = Additem::findOne($id);
if ($productItem instanceof Additem) {
$product = $productItem->product;
$pric = $productItem->price;
}

phpass matching input password with stored password

I used phpass to hash my password on Insert as follows
public function addAdmin(){
$this->load->library('phpass');
$this->load->database();
$psw = 'admin1234';
$hashed = $this->phpass->hash($psw);
$now = date("Y-m-d H:i:s");
$data = array(
'userid' => 'admin_user' ,
'userfname' => 'Admin' ,
'userlname' => 'Admin',
'userdname' => 'Admin' ,
'useraddress' => '20/72,Vidarshana Mawatha, Galawilawatta, Homagama' ,
'usercountry' => 'Sri Lanka',
'usercontactno' => '0112-892199' ,
'userlastlog' => $now ,
'userpassword' => $hashed ,
'userpermission' => '1',
'useremail' => 'dilukshanmahendra#gmail.com'
);
$this->db->insert('ecom-user', $data);
echo "Successfully Added!";
}
But when I input the same userid & password (Correct UserID and Password) at the Login where it validate by matching them with the stored ones, it returns '0' for the following where I expcted '1'
public function validateLogin($userid,$userpass){
$this->load->library('phpass');
$this->load->database();
$hashed = $this->phpass->hash($userpass);
$this->db->select('*');
$this->db->from('ecom-user');
$this->db->where('userid', $userid);
$this->db->where('userpassword', $hashed);
$result = $this->db->get();
echo $this->db->last_query();
echo '<br/>'.$result->num_rows();
}
Please some one help me to solve this
Better have a look here
, meanwhile, trim all input fields you've got for login and registering new users!