Help guys, is there any solution how to edit profile for logged in user, my code makes a change to all row, not a spesific row. it doesn't change only logged in user but for all user(row). So any idea?
here is my controller:
public function updateData(){
$param['first_name'] = $this->input->post('first_name');
$param['last_name'] = $this->input->post('last_name');
$param['email'] = $this->input->post('email');
$this->Model_members->updateData($param);
$data['title'] = "Passion";
$data['subtitle'] = "Synergize people";
$data['description'] = "Synergize people";
$data['view_isi2'] = "profile1";
$this->load->view('layouts/templates',$data);
}}
and this is my model:
public function updateData($param){
$field = array(
'first_name' => $param['first_name'],
'last_name' => $param['last_name'],
'email' => $param['email']
);
$this->db->update('users',$field);
$this->db->where('id',$this->session->userdata('$id'));
return 1;
}
very appreciate for the help!
You need to use $this->db->where() before $this->db->update()
why?:
because $this->db->update() runs the query, the next line is only a beginning trunck of sql query, which is not executed, therefor all rows are updated.
Related
I have some of the data, I want to save my data-id in array format. How can I do this? Below is my controller code.
Controller:
public function PostSaveRentCertificateReport(Request $request)
{
$report = $request->session()->get('report');
$reports = new Report;
$reports->column_one = $report->sum('column_one');
$reports->column_two = $report->sum('column_two');
// I want to save those id as array
$reports->adc_report_id = array('$report->id');
$reports->save();
$notification = array(
'message' => 'Report Created Successfully',
'alert-type' => 'success'
);
return redirect()->route('adc.pending.reports')->with($notification);
}
You can encode the data as JSON before saving it.
$reports = new Report;
$reports->column_one = $report->sum('column_one');
$reports->column_two = $report->sum('column_two');
$reports->adc_report_id = json_encode([$report->id]);
$reports->save();
But this will make it a bit more difficult to work with.
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.
I am having an error... I don't know how to fix this...
I am doing something that will set page privileges to admin employee and other roles.
But suddenly I doesn't get the value of my variable role.
public function login(Request $req)
{
$username=$req->input('email');
$password=$req->input('password');
$breadcrumb = 'Dashboard';
$pageTitle = 'CollabUX | Dashboard';
$prepath ='../';
$currentURL = Req::url();
$user = DB::table('add_users')->where(['username'=>$username,'password'=>$password])->get();
if(count($user)>0){
session(['isloggedin' => 'true']);
session(['roles' => $user->role]);
return View::make('dashboard')->with(
array('breadcrumb' => $breadcrumb,'pageTitle' => $pageTitle,'currentURL' => $currentURL,'prepath' => $prepath));
}
else{
//redirect page
$data = array(
'error' => 1,
'remarks' => 'Invalid Username/Password. Please try again.'
);
return View::make('login')->with('data', $data);
}
}
Well, there are two solutions.
You can define a user in code as admin
or you can create a separate table
userroles (id, title)
then you have to check with your requirements.
if only one user can have only role
then add userrole_id in users table and update accordingly.
if one user can have multiple roles
then create a separate table
users_to_userroles (id, user_id, userrole_id)
and it will be a pivot table.
So i have a model named Customer.
The db the Customer looks like this:
id, name, lastName, personal, address, zip, location, phones, emails updated_at, created_at
Emails and Phones is special rows because they are store as an json object example
['john#doe.com', 'some#othermail.com', 'more#mails.com']
I use the Customer Model to store the validation rules and custom messages like this
<?php
class Customer extends BaseModel
{
public function validationRules()
{
return array(
'name' => 'required|max:255',
'lastName' =>'max:255',
'personal'=> 'integer',
'location' => 'max:255',
'address' => 'max:255',
'zip' => 'required|integer',
'phones' => 'betweenOrArray:8,10|required_without:emails',
'emails' => 'emailOrArray'
);
}
public function validationMessages()
{
// returns Validation Messages (its too much to write down)
}
}
The OrArray Rule is found here https://stackoverflow.com/a/18163546/1430587
I call them through my controller like this
public function store()
{
$customer = new Customer;
$messages = $customer->validationMessages();
$rules = $customer->validationRules();
$input['name'] = Input::get('name');
$input['lastName'] = Input::get('lastName');
$input['personal'] = preg_replace("/[^0-9]/", "", Input::get('personal'));
$input['location'] = Input::get('location');
$input['address'] = Input::get('address');
$input['zip'] = Input::get('zip');
$input['emails'] = Input::get('emails');
$input['phones'] = Input::get('phones');
foreach($input['phones'] as $i => $value)
{
$input['phones'][$i] = preg_replace("/[^0-9]/", "", $value);
}
$validator = Validator::make($input, $rules, $messages);
}
This all works just fine, but I want to be able to PUT/PATCH request to update a single row.
But the validationRules has Required on certain fields so when its not present i cant update that single row. Without getting an error that the other fields (witch I'm not posting) is required.
How would I best approach this ?
You should get that instance of the model that represent the row you want to edit, that's why the resource controller's update method has a parameter that is the resource you want to edit.
public function update($resourceId) {
$customer = Customer::where('id', '=', $resourceId);
}
Now this customer has all the attributes you set before, so you can access them like:
$customer->name;
$customer->lastName;
So when you valide the values you can use the existing values in your validator where the input is empty:
$input['name'] = (Input::get('name')) ? (Input::get('name')) : $customer->name;
Or a prettier solution with the elvis operator:
$input['name'] = (Input::get('name')) ?: $customer->name;
I came up with another solution to this problem that works very well and its much cleaner.
$customer = Customer::find($id);
$input = Input::except('_method', '_token');
$customer->fill($input);
I read similar batch_update Qs but I still have issues. Thanks in advance for help! I receive error message ("One or more rows submitted for batch updating is missing the specified index.") for the following code:
Controller:
public function do_edit_page(){
$id = $this->input->post('page_id', TRUE);
$link_title = $this->input->post('page_link_title', TRUE);
$link = $this->input->post('page_link_sub_title', TRUE);
$this->content_model->update_links($id, $link_title, $link);
$this->index();
}
Model:
public function update_links($id, $link_title, $link){
$data = array(
array(
'page_id' => $id,
'link_title' => $link_title,
'link' => $link
)
);
$this->db->update_batch('content_links', $data, $id);
}
Check the CI documentation: http://ellislab.com/codeigniter/user-guide/database/active_record.html
The first parameter will contain the table name, the second is an associative array of values, the third parameter is the where key.
so the third parameter should be a column not data.