PDO Update 1 column multiple rows with array - php

I am struggling to workout a good method to update one column of my wcx_options table.
The new data is sent fine to the controller but my function isn't working at all.
I assumed i could loop through each column by option_id updating with the values from the array.
The database:
I update the option_value column with the new information via a jQuery AJAX Call to a controller which then calls a function from the backend class.
So far i have the following code:
if(isset($_POST['selector'])) {
if($_POST['selector'] == 'general') {
if($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' && isset($_POST['token'])
&& $_POST['token'] === $_SESSION['token']){
$site_name = $_POST['sitename'];
$site_url = $_POST['siteurl'];
$site_logo = $_POST['sitelogo'];
$site_tagline = $_POST['sitetagline'];
$site_description = $_POST['sitedescription'];
$site_admin = $_POST['siteadmin'];
$admin_email = $_POST['adminemail'];
$contact_info = $_POST['contactinfo'];
$site_disclaimer = $_POST['sitedisclaimer'];
$TimeZone = $_POST['TimeZone'];
$options = array($site_name, $site_url, $site_logo, $site_tagline, $site_description, $site_admin, $admin_email,$contact_info, $site_disclaimer, $TimeZone);
// Send the new data as an array to the update function
$backend->updateGeneralSettings($options);
}
else {
$_SESSION['status'] = '<div class="error">There was a Problem Updating the General Settings</div>';
}
}
}
This is what i have so far in terms of a function (It doesnt work):
public function updateGeneralSettings($options) {
$i = 1;
foreach($options as $option_value) {
$where = array('option_id' => $i);
$this->queryIt("UPDATE wcx_options SET option_value='$option_value' WHERE option_id='$where'");
$i++;
}
if($this->execute()) {
$_SESSION['success'] = 'Updated General Settings Successfully';
}
}

With the given DB-layout i'd suggest to organize your data as assiciative array using the db fieldnames, like:
$option = array(
'site_name' => $_POST['sitename'],
'site_url' => $_POST['siteurl'],
// etc.
'timeZone' => $_POST['TimeZone']
);
And than use the keys in your query:
public function updateGeneralSettings($options) {
foreach($options as $key => $value) {
$this->queryIt("UPDATE wcx_options SET option_value='$value' WHERE option_name='$key'");
if($this->execute()) {
$_SESSION['success'] = 'Updated General Settings Successfully';
}
}
}
(However, are you sure, you do not want to have all options together in one row?)

Change your query, you try to use an array as where condition. In the syntax you used that won't work. Just use the counter as where condition instead of define a $where variable. Try this:
public function updateGeneralSettings($options) {
$i = 1;
foreach($options as $option_value) {
$this->queryIt("UPDATE wcx_options SET option_value='$option_value' WHERE option_id='$i'");
$i++;
}
if($this->execute()) {
$_SESSION['success'] = 'Updated General Settings Successfully';
}
}

Related

Automatically filling in sql column data after referencing a substring of another column

Currently I'm using Mysql and CodeIgniters MVC framework to fill in my data. The table logs every status change that has been made and when it was made. This is what the database currently looks like:
I've added new columns in the table called status_from and status_to, where I want these columns to take the substring from action column.
But now how do I display it in my database with my following code:
Controller class:
public function status($status){
$statusar = array('D'=>'Draft','N'=>'Unpublish','Y'=>'Publish','U'=>'Action','L'=>'Unlisted','S'=>'Sold','T'=>'Let');
if($this->input->post('id')){
foreach($this->input->post('id') as $key => $id):
$check = $this->listings_model->loadlisting_check($id);
$log = "Listing website status changed from ". $statusar[$check->status]." to ".$statusar[$status].". The listing ID is #".$id.".";
$this->logs_model->insert_log(array('refno'=>$check->refno,'action'=>trim($log)));
$data=array('status'=>$status);
if($status == 'T' || $status == 'Y' || $status == 'S'){
$pub = 1;
}else{
$pub =0;
}
$this->listings_model->lpupdate(array('property_publish'=>$pub),$id);
endforeach;
}
return true;
}
listings_model:
function loadlisting_check($id)
{
$this->db->select("refno, status, archive");
$id=$this->db->escape_str($id);
$cond=array("$this->table_name.$this->primary_key"=>$id);
$this->db->where($cond);
$this->db->from($this->table_name);
$query = $this->db->get();
return $query->row();
}
logs_model:
public function insert_log($log)
{
$log['agent_id'] = $this->session->userdata('clientsessuserid');
$log['logtime'] = date('Y-m-d H:i:s');
$this->db->insert($this->table_name, $log);
return true;
}
Basically I want to fill my status_from column with $statusar[$check->status] and status_to column with $statusar[$status] when every new entry is made
You can pass the variables you want to add in the array in insert_log method parameter with proper key matched with column name in your table
public function status($status){
$statusar = array('D'=>'Draft','N'=>'Unpublish','Y'=>'Publish','U'=>'Action','L'=>'Unlisted','S'=>'Sold','T'=>'Let');
if($this->input->post('id')){
foreach($this->input->post('id') as $key => $id):
$check = $this->listings_model->loadlisting_check($id);
$log = "Listing website status changed from ". $statusar[$check->status]." to ".$statusar[$status].". The listing ID is #".$id.".";
$this->logs_model->insert_log(array('refno'=>$check->refno,'action'=>trim($log) , 'status_from'=>$statusar[$check->status] ,'status_to'=>$statusar[$status]));
$data=array('status'=>$status);
if($status == 'T' || $status == 'Y' || $status == 'S'){
$pub = 1;
}else{
$pub =0;
}
$this->listings_model->lpupdate(array('property_publish'=>$pub),$id);
endforeach;
}
return true;
}
And you will not need to add anything else to your model

else condition is working even if is true

I'm using codigniter 3.1.2 and using simple if condition in php but really confused when I checked my condition is true getting result from else condition as well and if as well mean getting data in from both cases.
public function editexperience($UserID = 0, $ID = 0) {
if ($this->Access->HaveAccess('Edit')) {
$Row = $this->Experience->Row($ID);
if ($ID > 0 && $Row){
print_r($Row);
Def(array(
'Update'=>'users/submit/updateexperience/'
),'Actions');
$User = $this->Model->Row(intval($UserID), '', 'CTRY.Currency');
$ID = intval($ID);
$Data['Row'] = $Row;
Def($Row,'Row');
$Data['Title'] = 'Edit Experience';
$Data['Fields'] = $this->GetExperienceFields($User->Currency, true);
$this->Main->SetPage('Helper/Edit', $Data, true);
} else {
TempNote('There is problem while getting request data!', 'Error');
redirect(URI(_E('{Page.List}'), true), 'refresh');
die();
}
}
}
In code I mentioned if I have Row then load template of edit.
Suppose:
I have Row and its loading edit template and also showing the error of else condition really confuse what is happening.
My PHP version is 5.6.31
TempNote Function
function TempNote($Message, $Type) {
//Prepare Data
$Current = array('Message'=>$Message,'Type'=>$Type);
//Get current instance
$Ins = & get_instance();
$Old = $Ins->Main->Messages;
// If another is already set and that should not be current
if (!empty($Old)) {
foreach ($Old as $Key=>$Now) {
if ($Now === $Current){
unset($Old[$Key]);
}
}
}
$Ins->Main->Messages[] = $Current;
$Ins->session->set_flashdata('Message', $Ins->Main->Messages);
}

Codeigniter on duplicate key insert

i want to create a condition which a user would choose whether he wants to use an input which means a database would create an auto_incremented id or he wants to use an older data which will not use new id but only use it. i have used dropdown database populate for my old input.
My Dropdown list
//get contractor list
$Contractor_List = $this->foo_pro->get_list_contractors();
$opt = array('' => '');
foreach ($Contractor_List as $Contractor_No) {
$opt[$Contractor_No] = $Contractor_No;
}
$data['con_list'] = form_dropdown('',$opt,'','ProjectID = "Contractor_No" name="contractorNo" id="" class="w3-select w3-border w3-hover-light-grey"');
My Controller
public function save_createdProject()
{
$data_project = array();
$data_contractor = array();
//project data
if ($this->input->post('year') === '') {
$data_project['P_Year'] = 15;
}else{
$data_project['P_Year'] = $this->input->post('year');
}
if ($this->input->post('code') === '') {
$data_project['Code'] = 'KO';
}else{
$data_project['Code'] = $this->input->post('code');
}
$data_project['ProjectID'] = $this->input->post('project');
$data_project['Contract_Amount'] = $this->input->post('camount');
//contractor data
if ($this->input->post('cname') === '' && $this->input->post('caddress') === '') {
$data_project['Contractor_No'] = $this->input->post('contractorNo');
}else{
$data_contractor['Contractor_Name'] = $this->input->post('cname');
$data_contractor['Contractor_Address'] = $this->input->post('caddress');
}
$this->foo_pro->add_project($data_project, $data_contractor);
redirect('Main/project','refresh');
//var_dump($data);exit;
}
My Model
public function add_project($data_project, $data_contractor)
{
//contractor
$this->db->insert('contractor', $data_contractor);
$Contractor_No = $this->db->insert_id();
//project
$data_project['Contractor_No'] = $Contractor_No;
$this->db->insert('project', $data_project);
$ProjectID = $this->db->insert_id();
}
this here is my problem except inserting the older data which is the contractor_no 1 it creates another data that would insert as contractor_no 4.. but also i need to insert new data for new contractor_name..

Putting data base values into array shows error in codeigniter

I am taking data from many tables. I want to display many objects in different places. I got the data from data base, but I want to put the data into an array for useful purpose, but it's not working.
This my controller code:
public function compare_by_business_sectors() {
//print_r($this->input->post());exit;
if ($this->input->post())
{
$solution_array = array();
//print_r (json_encode($business_sectors)); exit;
$business_sectors=$this->home_model->compare_business_sectors_data($this->input->post());
$tab_child_id = "";
$id="";
foreach ($business_sectors as $key=>$sectors) {
$solution_array[1]=$sectors->solution_name;
$solution_array[2]=$sectors->description;
$solution_array[3]=$sectors->vendor_name;
$solution_array[4]=$sectors->video_presentation;
$solution_array[5]=$sectors->start_free_trail;
$solution_array[6]=$sectors->hardware_package;
$solution_array[7]=$sectors->pos_market_rating;
//$solution_array[$sectors->field_id] = $sectors->value;
$id = "solution".$sectors->tab_child_id;
if ($tab_child_id != $sectors->tab_child_id) {
$id = array();
$id[$sectors->field_id] = $sectors->title;
}
else if ($tab_child_id == $sectors->tab_child_id) {
$id[$sectors->field_id] = $sectors->title;
}
}
//$solution_array[$id]= $id;
}
print_r($id);
//$this->load->view('compare_by_business_sectors.php');
}
This is my model code:
public function compare_business_sectors_data($sectorid) {
$query = $this->db->select('solutions.*,solution_tabs_child_fields.field_id,solution_tabs_child_fields.tab_child_id,solution_tabs_child_fields.title')
->from('solutions')
//->join('solutions', 'business_sector.sector_id = solutions.business_sector_id',"left")
->join('solution_features','solutions.entry_id = solution_features.entry_id',"left")
->join('solution_tabs_child_fields','solution_features.field_id = solution_tabs_child_fields.field_id')
->where('solutions.business_sector_id', $sectorid['id'])
->get();
return $query->result();
//print_r($query->result());exit;
}
change it as follow and try.
$id_string = "";
$id_array = array();
foreach ($business_sectors as $key=>$sectors) {
$solution_array[1]=$sectors->solution_name;
$solution_array[2]=$sectors->description;
$solution_array[3]=$sectors->vendor_name;
$solution_array[4]=$sectors->video_presentation;
$solution_array[5]=$sectors->start_free_trail;
$solution_array[6]=$sectors->hardware_package;
$solution_array[7]=$sectors->pos_market_rating;
//$solution_array[$sectors->field_id] = $sectors->value;
$id_string = "solution".$sectors->tab_child_id;
if ($tab_child_id != $sectors->tab_child_id) {
$id[$sectors->field_id] = $sectors->title;
}
else if ($tab_child_id == $sectors->tab_child_id) {
$id[$sectors->field_id] = $sectors->title;
}
}
print_r($id_string);
print_r($id_array);
First you are assigning string value to $id then, $id will convert to array only if first if() statement execute other wise it will not be a string. So to overcome from this keep $id_array before for loop and you can capture string in another variable.

Retrieving value from database in CodeIgniter is not working

In my Codeigniter project ,table value is not retrieving from database.Am using MySQL (WAMP) as database.Using Select Query i have checked the data in database and its fine there.When updating the same also its retrieving the old value in db.But when retrieving the value in later stage (ie,taking old bill) its not retrieving the value.The problem is happening only on the single field(ie,actual_price).How to solve this error.Here am attaching the screenshot and controller code for the same.
Controller Code
function bill_view($billid)
{
if(!$billid) {
redirect('report/bill_report');
}
$salecode =str_replace("_","/",$billid);
$filter ="gm_sale.saleCode ='$salecode'";
$billArray =$this->sale_model->getBillinfo($filter);
$exshowroom='';
$bank ='';
$scheme='';
$wcoNo ='';
$saleId =0;
foreach($billArray as $key=>$val) {
$exshowroom = $val['actual_price'];
$date =$val['saledate'];
$sale_to=$val['saleCustomer'];
$saleUserId=$val['saleUserId'];
$wcoNo = $val['wcoNo'];
$saleId= $val['saleId'];
if(!is_null($val['bank']) && !empty($val['bank'])){
$bank =$val['bank'];
}
if(!is_null($val['scheme_id']) && !empty($val['scheme_id'])){
$array_scheme = unserialize($val['scheme_id']);
///////////////////////////////////////////
foreach ($array_scheme as $val_scheme_id) {
$res_scheme = $this->db->get_where("gm_scheme",array('id'=>(int)$val_scheme_id));
if($res_scheme->num_rows >0){
$arrscheme = $res_scheme->row_array();
if(!empty($scheme)) {
$scheme .= ",";
}
$scheme .= $arrscheme['schemeName'];
}
}
/////////////////////////////////////////////
}
break;
}
$query = $this->db->get_where('gm_users',array('userId'=>(int)$saleUserId));
if($query->num_rows >0) {
$arrUser =$query->row_array();
}else{
$arrUser =array();
}
$data['list_product'] = $billArray;
$data['exshowroom']=$exshowroom;
$data['userinfo'] =$arrUser;
$data['saleCode'] =$salecode;
$data['sale_to'] =$sale_to;
$data['added_date'] =$date;
$data['bank'] =$bank;
$data['scheme'] =$scheme;
$data['wcoNo'] =$wcoNo;
$data['saleId'] =$saleId;
$this->load->view('header_login');
$this->load->view('report/bill_view',$data);
//print_r($billArray);
$this->load->view('footer_login');
}
Model Code
function getBillinfo($filter=''){
$this->db->select('*,gm_sale.added_date as saledate');
$this->db->from('gm_sale',FALSE);
$this->db->join('gm_products',"gm_sale.productId=gm_products.productId",FALSE);
$this->db->join('gm_model',"gm_products.model_id=gm_model.id",FALSE);
$this->db->join('gm_banks',"gm_sale.bank_id=gm_banks.bank_id","LEFT");
if($filter<>"")
$this->db->where($filter,'',FALSE);
$this->db->order_by('gm_sale.saleId',"desc");
$query = $this->db->get();
print_r($query);
if($query->num_rows>0) {
$arrRow =$query->result_array();
print_r($arrRow);
return($arrRow);
}
return(array());
}
Your code that you have in the controller doing DB stuff should be in the model.
The controller does not have context to
$this->db
modify your joins (3rd param) to retrieve values in actual_price

Categories