cakephp can't update table with set - php

I have a problem with updating database table in cakephp...
So I have a profile page where the logged in user can see and update his personal information. Here is my solution for it (yes I know it's not the best...)
if($this->request->is('post')) {
$data = $this->request->data['user-profile'];
// $uid = $this->Session->read("WebUser.id");
$uid = 1;
$user_data = $this->WebUser->find('first', array('conditions'=>array('id'=>$uid)));
$updated_fields = '';
foreach($data as $key => $value) {
if($key != 'state'){
if(empty($value)) {
$this->Session->setFlash("Please fill in all the required fields");
return;
}
}
if($user_data['WebUser'][$key] != $value) {
if($key == 'email') {
$mail_check = $this->WebUser->find('first', array('conditions'=>array('email'=>$value, 'id !='=>$uid)));
if($mail_check) {
$this->Session->setFlash("This e-mail is already registered");
return;
}
}
$updated_fields .= "'".$key."'=>'".$value."',";
}
}
if($updated_fields != '') {
$updated_fields .= "'modified'=>'".date("Y-m-d H:i:s")."'";
$this->WebUser->read(null, $uid);
$this->WebUser->set(array('first_name'=>'John','modified'=>'2014-12-30 10:53:00'));
if($this->WebUser->save()) {
$this->printr($this->data);
$this->WebUser->save();
$this->Session->setFlash("Success : Profile data is now modified", array("class"=>"success_msg"));
} else {
$this->Session->setFlash("Error : Data modifying isn't complete. Please try again!");
}
}
return;
}
So this code fetches the user info from the database and looks for those fields which are edited on profile page. Problem is when I want to save the data it give me back false and didn't save it... Does someone have a solution for this?

Try putting
$this->WebUser->validationErrors;
in else part and check whether there are any validation errors or not.
Like this:
if($this->WebUser->save()) {
$this->printr($this->data);
$this->WebUser->save();
$this->Session->setFlash("Success : Profile data is now modified", array("class"=>"success_msg"));
} else {
echo "<pre>";print_r($this->WebUser->validationErrors);die();
$this->Session->setFlash("Error : Data modifying isn't complete. Please try agin!");
}

Did you tried to set id directly?
$this->WebUser->id = $uid;
Also, CakePHP is automatically update modified field in your table after any transactions. So you don't have to set it directly (but you can if you want any other date value).
About validation. I recommend you to read about Data Validation in CakePHP, because that validation is not good, it's can be handled by models.
Also. You can get any validation errors from models using Model::$validationErrors.
debug($this->Recipe->validationErrors);

The problem with this code was that didn't wanted to save the posted data ( debug($this->WebUser->save) has give me back false). At the end I didn't found the solution why this code not worked but the conclusion is that you never need to use more users table than one. So now I have a Users and Groups tables, and different type of users are connected to their groups(Admin, User, ...).

Related

value stored as array in the database getting deleted while adding new values into the same array while updating

Here my problem is when i go for updating the values already stored in the database is getting deleted and only the newly added values are getting
here is my code
<script>
$(document).ready(function() {
if(destId=='bar3' || sourceId=='bar3') {
var itemvalue2 =Array();
$('ul#bar3 li').each(function() {
itemvalue2.push($(this).attr("value"));
});
document.getElementById("bar3-output").value=itemvalue2;
}
});
</script>
here is my view
<ul id="bar3" class="block__list block__list_tags">
<input type="hidden" id="bar3-output" name="all_active_menu3" class="form-control"
value="<?php if(!empty($team_info->members)) {
$tagsArray = explode(',', $team_info->members);
$tagsLinksArray = array();
foreach($tagsArray as $tag) {
$tagName = trim($tag);
$tagsLinksArray[]=$tagName;
}
$tagsLinks = implode(',', $tagsLinksArray);
echo $tagsLinks;}?>
">
</ul>
Here is my control
public function save_team($team_id = NULL)
{
$profile_data=$this->Teams_model->array_from_post(array('team_name'));
$this->Teams_model->_table_name = 'tbl_teams'; // table name
$this->Teams_model->_primary_key = 'team_id'; // $id
if (!empty($team_id)) {
$profile_data['members']=$this->input->post('all_active_menu3');
$this->Teams_model->save($profile_data, $team_id);
} else {
$profile_data['members']=$this->input->post('all_active_menu3');
$this->Teams_model->save($profile_data);
}
if (!empty($team_id)) {
$message = ('Team Info Updated');
} else {
$message = ('Team Info Saved');
}
$type = 'success';
set_message($type, $message);
redirect('admin/team/team_list'); //redirect page
}
the value in the database is not becoming stable i had used many ideas but didn't reached destination.hope your help please help me
I'm not certain how your code works but here is what my guess is and what is going wrong: You're just replacing the old value in both cases.
This seems to be the relevant code fragment.
$profile_data=$this->Teams_model->array_from_post(array('team_name'));
//...
if (!empty($team_id)) {
$profile_data['members']=$this->input->post('all_active_menu3');
$this->Teams_model->save($profile_data, $team_id);
} else {
$profile_data['members']=$this->input->post('all_active_menu3');
$this->Teams_model->save($profile_data);
}
The first assignment of $profile_data reads the current team data from the existing team. Your naming is a bit confusing as you're not actually reading any POST data it seems. The assignment within the if block that would fulfill the condition !empty($team_id) should update the team members and the false block should create a new team. Did you verify that $team_id gets set successfully?
I'm not certain about the structure of the team information but rather than a straight assignment using = in the true block you should be using += or manually combine the new and old data and do the assignment afterwards.
Using something like array_merge or a loop to create an intermittent object to hold the combined data should work here.

NULL Value inserted in Database (Codeigniter)

I Am trying to insert data in DB,But somehow NULL is inserted in DB
Here Is My Controller
foreach($this->input->post('resume_id') as $key =>$value ){
$ResumeInsert[$key]['resume_keyid'] = $Resume['resume_id'][$key];
$ResumeInsert[$key]['employer_name'] = $Resume['employer_name'][$key];
$ResumeInsert[$key]['start_Date'] = $Resume['start_Date'][$key];
$ResumeInsert[$key]['end_date'] = $Resume['end_date'][$key];
$ResumeInsert[$key]['type_id'] = $Resume['type_id'][$key];
$ResumeInsert[$key]['position'] = $Resume['position'][$key];
$ResumeInsert[$key]['responsibility'] = $Resume['responsibility'][$key];
$ResumeInsert[$key]['Skills'] = $Resume['Skills'][$key];
if(isset($Resume['id'][$key]) ){
$Key_Resume__ExistIDs[]=$Resume['id'][$key];
$ResumeUpdate[$key]=$ResumeInsert[$key];
$ResumeUpdate[$key]['resume_id']=$Resume['id'][$key];
unset($ResumeInsert[$key]);
}
else{
$ResumeInsert[$key]['resume_id'] = $GetLastID;
print_r ($ResumeInsert[$key]);exit;
$GetLastID++;
}
}
$idsToDelete='';
if(empty($ResumeInsert) && empty($ResumeUpdate)){
$idsToDelete=array_diff($Key_Resume_IDs,$Key_Resume__ExistIDs);
}
$status=$this->Resume_model->ProcessData($idsToDelete,$ResumeUpdate,$user_id,$ResumeInsert,$imgInsert,$imgUpdate);
redirect('Resume','refresh');
Here Is My Code Of Model
function ProcessData($idsToDelete,$tbl_resumeUpdate,$user_id,$tbl_resumeInsert,$imgInsert,$imgUpdate){
$this->db->trans_start();
if(!empty($idsToDelete)){
$this->delete_tbl_resume($idsToDelete);
}
if(!empty($tbl_resumeUpdate)){
//echo "up";exit;
$this->update_tbl_resume($tbl_resumeUpdate);
}
if(!empty($tbl_resumeInsert)){
//echo "int";exit;
$this->insert_tbl_resume($user_id,$tbl_resumeInsert);
}
if(!empty($imgInsert)){
$this->insert_tbl_file_paths($imgInsert);
}
if(!empty($imgUpdate)){
$this->update_tbl_file_paths($imgUpdate);
}
return $this->db->trans_complete();
}
This is Insert Query
function insert_tbl_resume($id,$arrtbl_resume){
$this->db->insert_batch('tbl_resume', $arrtbl_resume);
}
In Above Code,Null Value inserted In DB.
when i Print above query,it displays blank
Any Help Please?
You should use form_validation library. I'm giving you an example, you can edit and use it.
In autoload.php, edit $autoload['libraries'] = array(); line to:
$autoload['libraries'] = array('form_validation');
Then, use form_validation in your controller file. For example:
$this->form_validation->set_rules('resume_keyid', 'Resume ID', 'required');
if ($this->form_validation->run() == FALSE)
{
$this->index() // if there is an error, user will redirect to this function
}
else
{
$this->Resume_model->ProcessData();
}
Also please use $this->input->post('resume_keyid', TRUE); structure in your model. "TRUE" means "open XSS filter". Because in CI 3, it comes off as default. If you don't want it, just remove. If you use CI 2, you don't need to add "TRUE".
A few suggestions:
1 - Don't use camelization when you name functions. For example; use process_data() instead of processData()
2 - Check CI Form Validation Document for all details (E.g. all references)
3 - I think you can use $this->db->insert();, just create an array and POST it. If you make it, you'll understand what's wrong.

CakePHP form not posting

I am working on a page that can update the sales agent on a specific order.
I made the list of options and a dropdown list is created.
Heres in the controller:
$order = $this->Order->read(null,$id);
$this->set("order",$order);
if ($this->request->is("post")) {
if($this->Order->save($this->request->data)) {
$this->Session->setFlash("Sales Agent Updated");
}
}
Heres the view:
echo $this->Form->create("Order");
echo $this->Form->input("OrderID");
echo $this->Form->input("UserID");
echo $this->Form->submit("Submit");
echo $this->Form->end();
When I submit the data, it appears that the data is saved, (the flash message is set).
However, when I then preset the fields with data that is already in the database, all the sudden it doesn't even post. (I put a debug after the reques->is("post) condition which doesnt show up after I submit).
$order = $this->Order->read(null,$id);
$this->set("order",$order);
if ($this->request->is("post")) {
if($this->Order->save($this->request->data)) {
$this->Session->setFlash("Sales Agent Updated");
}
}
if (!$this->request->data) {
$this->request->data = $order;
}
The input fields are correctly pre filled, but now the form doesn't even post.
Does anybody know whats wrong?
Thanks!
Update your controller code to:
$order = $this->Order->read(null,$id);
$this->set("order",$order);
if ($this->request->is('post') || $this->request->is('put')) {
if($this->Order->save($this->request->data)) {
$this->Session->setFlash("Sales Agent Updated");
}
}
Now put a debug after the reques->is('post') condition which will show what you need to show.

Why this codeigniter function parameter isn't working as it should be?

I'm trying to create callback script for Coinbase bitcoin payments. Here is the below function from my payment controller. But somehow the key isn't working as it should. I am trying to access it like that: http://www.example.com/payments/callback?key=true but it's not getting affected basically not working. Take a note that the script is working itself but after adding the key function and validating it ... it's not anymore. The issue is caused by that but I don't know what exactly, so what may cause that in the script below?
Thanks for taking the time to check and possibly answer my question.
function is_valid_key($key) {
// logic to check key
$valid = true;
if($valid) {
return true;
}
else {
return false;
}
}
function callback()
{
//Check if key is valid.
$key = $this->input->get('key');
if( ! $this->is_valid_key($key)) {
//If key above is valid order is "completed", please proceed.
$data = json_decode(file_get_contents('php://input'), TRUE);
$status = $data['order']['status'];
$userid = '507';
if (($status === 'completed')) {
$this->db->query( 'update users set user_money=user_money+15, user_credits=user_credits+5 WHERE users_id=' . $userid );
}
}
}
it has to do with your configuration settings. check out this question Enabling $_GET in codeigniter
Also you can use
parse_str($_SERVER['QUERY_STRING'], $_GET);
which would push GET right back on

Using flashdata while posting same controller twice in Codeigniter

I am trying to submit a EDIT form which edits Users Academics Details,
These Details have unique id in DB and my Code in Short Looks like below :
class edit extends ci_controller
{
function user_academics($id = NULL)
{
if(isset($id) == FALSE) //if link is ./edit/user_academics
{
$id = NULL;
$link = site_url('profile');
show_error("Invalid Page Request! <a href='$link' Go to Profile </a>");
}
$user_id = $this->session->userdata('user_id');
$data['fill'] = $this->edit_model->get_user_academics($id);
if($user_id != $data['fill']['user_id']) // check if logged in user is accessing his record or others
{
$link = site_url('profile');
show_error("This is an Invalid Request ! <a href='$link'>Go to Profile </a>");
}
else // actual work starts here
{
$this->session->set_flashdata('ua_id',$id); // update_academics will get this data
$this->load->view('edit/edit_3_view',$data);
}
}
function update_academics()
{
$ua_id = $this->session->flashdata('ua_id'); // flash data used here .
if( !$ua_id )
{
show_error('Sorry, This request is not valid!');
}
$academics = array(
// All post values
);
$this->edit_model->update_user_academics($academics,$ua_id);
//print_r($academics);
redirect('profile');
}
}
Now the problem is
- If I open two different records to edit, then It will set only one Session Flash value.
- And No matter what I edit , the existing values of the last flash value gets updated.
Please Suggest me another way or Correct me if I am wrong in above code . Thanks
save that flashdata in array, like:
$myArr = array('value 1', 'value 1');
//set it
$this->session->set_flashdata('some_name', $myArr);
And in view:
$dataArrs = $this->session->flashdata('some_name');
//loop thru $dataArrs to show the flashdata
Flash data is simply like variable which is available only in next request, you can bypass this behavior by using two different keys with record id in it, so that when you use flash data for showing message you can access key with particular record id.

Categories