function updateUser($userData, $statsID) {
$fields = '';
$config = 0;
while(list($key,$val)= each($userData)) {
if($config++ != 0){
$fields .= ' , ';
}
$col = $key;
$val = $val;
$fields .= "$col='$val'";
}
//echo $fields;
global $dbhandle;
$query = mysqli_query($dbhandle, "UPDATE data SET $fields WHERE statsID = '$statsID'");
echo var_export($query); <--returns NULL
In this code, I pass in an array as noted below:
$sendData = array('name'=>$name,'race'=>$race,'rank'=>$rank,'highestRank'=>$highestRank,'commander'=>$commander,'atkSld'=>$atkSld,'atkMerc'=>$atkMerc,'defSld'=>$defSld,'defMerc'=>$defMerc,'untSld'=>$untSld,'untMerc'=>$untMerc,'spies'=>$spies,'sentries'=>$sentries,'morale'=>$morale,'tff'=>$tff,'strike'=>$strike,'strikeRank'=>$strikeRank,'defense'=>$defense,'defenseRank'=>$defenseRank,'spy'=>$spy, 'spyRank'=>$spyRank, 'sentry'=>$sentry, 'sentryRank'=>$sentryRank, 'fort'=>$fort,'siege'=>$siege,'economy'=>$economy,'tech'=>$tech,'conscription'=>$conscription,'gold'=>$gold,'tbg'=>$tbg,'gameTurns'=>$gameTurns,'covertLvl'=>$covertLvl);
I have confirmed all the data is set and correct. The statsID passes in correctly and when I echo field, it gives me exactly what is required to fulfill my query and in the correct format (key='value' , key ='value' , key ='value etc)
EDIT: Problem solved, I have updated my code to reflect the solution. For some reason I had to call global $dbhandle prior to the query string. If someone could tell me why that would be great!
Related
I am doing update in zend which in some cases doesn't update all the fields, the fields that are not updated become null as if we are doing an add.
This is the code from the Controller
$result = $theuserModel->updateUserTest(
$id,
$this->getRequest()->getPost('user_name'),
/*some code*/
$this->getRequest()->getPost('user_postee')
);
if ($result) {
$this->view->notif = "Successfull Update";
return $this->_forward('index');
}
The corresponding model
public function updateUserRest($id, $nom,$poste)
{
$data = array(
'user_name' => $nom,
'user_postee' => $poste
);
$result=$this->update($data, 'user_id = '. (int)$id);
return $result;
}
I do an update for user_name only I found that the old value of user_postee got deleted and replaced by the default value (initial value which we get at the time of creation) for example null.
Thanks in advance!
I have done this changes (bad solution) If anyone has another one optimised
->Controller
if($this->getRequest()->getPost('user_name')){
$resultname=$userModel->updateUserName($id,$this-
>getRequest()->getPost('user_name'));
}
if($this->getRequest()->getPost('user_postee')){
$resultpostee=$userModel->updateUserPoste($id,$this-
>getRequest()->getPost('user_postee'));
}
if ($resultname|| $resultpostee){
$this->view->notif = "Mise à jour effectuée";
return $this->_forward('index');
}
-> Model
public function updateUserName($id, $name)
{
$data = array(
'user_name' => $name
);
$result=$this->update($data, 'user_id = '. (int)$id);
return $result;
}
public function updateUserPostee($id, $postee)
{
$data = array(
'user_postee' => $poste
);
$result=$this->update($data, 'user_id = '. (int)$id);
return $result;
}
that is complete correct response of update in Zend Db Table.
I believe your assumption is if the value of 'user_postee' is null then it should not be updated into the database, am I correct.
The answer is they will update the new value of "NULL" into the database.
To avoid it , what you should do is
using fetchrow() to get the value of the line by id
foreach user_name and user_postee check if the value of them matching the array value your fetched , if nothing changed or Null, then use the old value from array , if new value exist use new value insert into the array , finally use update to update the new array into database
Assume your Table Column is also "user_name" and "user_postee"
public function updateUserRest($id, $nom,$poste)
{
$row = $this->fetchRow('user_id = '. (int)$id);
if(!empty($nom) && $row['user_name'] != trim($nom)){
$row['user_name'] = $nom;
}
if(!empty($poste) && $row['user_poste'] != trim($poste)){
$row['user_poste'] = $poste;
}
$result=$this->update($row, 'user_id = '. (int)$id);
return $result;
}
I have a problem with creating a query through a function (all others variables works correctly) I have a function that doesn't print variables correctly (exactly $NomiFarmacie and $day)
//The problem is present in this function
function Cicla($Periodo, $FarmacieRiordinate, $Query) {
global $tabella_calendario, $count; //them works
foreach ($Periodo as $giorno) {
$day = $giorno->format("Y-m-d");
$NomiFarmacie = addslashes($FarmacieRiordinate[$count % count($FarmacieRiordinate)]);
echo $NomiFarmacie; echo $day; //Both are correct
print_r($Query); //Queries are not completed correctly. OUTPUT Below
$count++;
}
}
$FarmacieRiordinate = $_POST['elementi'];
$DataIniziale = $_POST['data1'];
$DataFinale = $_POST['data2'];
$Query = ("UPDATE $tabella_calendario SET Farmacia='$NomiFarmacie' WHERE Data='$day'");
Cicla(CalcolaPeriodo($DataIniziale, $DataFinale), $FarmacieRiordinate, $Query);
A PORTION OF OUTPUT print_r($Query)
UPDATE calendario SET Farmacia='Array' WHERE Data='1546297200'
UPDATE calendario SET Farmacia='Array' WHERE Data='1546297200'
UPDATE calendario SET Farmacia='Array' WHERE Data='1546297200'
UPDATE calendario SET Farmacia='Array' WHERE Data='1546297200'
The problem is your $Query already be combined as string BEFORE passed into your function.
You can use vsprintf in this case.
function Cicla($Periodo, $FarmacieRiordinate, $Query) {
global $tabella_calendario, $count; //them works
foreach ($Periodo as $giorno) {
$day = $giorno->format("Y-m-d");
$NomiFarmacie = addslashes($FarmacieRiordinate[$count % count($FarmacieRiordinate)]);
echo $NomiFarmacie; echo $day; //Both are correct
$realQuery = vsprintf($Query, array($NomiFarmacie, $day));
print_r($realQuery); //Queries are not completed correctly. OUTPUT Below
$count++;
}
}
$FarmacieRiordinate = $_POST['elementi'];
$DataIniziale = $_POST['data1'];
$DataFinale = $_POST['data2'];
$Query = ("UPDATE $tabella_calendario SET Farmacia='%s' WHERE Data='%s'");
Cicla(CalcolaPeriodo($DataIniziale, $DataFinale), $FarmacieRiordinate, $Query);
You can read more about vsprintf here:
http://php.net/manual/en/function.vsprintf.php
.
I dont know why after clicking the "Add Button", the items that needs to insert into the database is NULL.
so here's my controller
public function addItem(){
$data = array(
"item_ID"=>$_POST['item_ID'],
"itemName"=>$_POST['itemName'],
"itemDescription"=>$_POST['itemDescription'],
"itemLink"=>$_POST['itemLink']
);
$orgID = $this->model->get_org();
$this->model->insertItem($data,$orgID);
}
and here's my model
public function insertItem($data,$orgID){
$this->db->insert('Items',$data);
$getID=$this->db->insert_id();
foreach($orgID as $temp):
$Organization_ID = $_POST[$temp->OrganizationID];
endforeach;
$SkillReq=$this->input->post('0');
$Skill_ReqID=$this->input->post();
$insertdata = array();
for($i=0; $i=count($orgID); $i++){
$insertdata[]=array(
'Skill_ReqID'=>$Skill_ReqID[$i],
'OrganizationID'=>$Organization_ID[$i],
'item_ID'=>$getID[$i],
'SkillReq'=>$SkillReq[$i]
);
}
$this->db->insert_batch('skillreqdept',$insertdata);
}
it actually inserts the rows that had been counted in orgID but there is no data, only the Auto Incremented skill_reqID has in it.
I thing the issue is with Skill_ReqID'=>null[$i], I dont know what is null variable.
Please try the following:
public function insertItem($data,$orgID){
$this->db->insert('Items',$data);
$getID=$this->db->insert_id();
foreach($orgID as $temp):
$Organization_ID = $_POST[$temp->OrganizationID];
endforeach;
$SkillReq=$this->input->post('0');
$insertdata = array();
for($i=0; $i=count($orgID); $i++){
$items=array(
'OrganizationID'=>$Organization_ID[$i],
'itemID'=>$getID[$i],
'SkillReq'=>$SkillReq[$i]
);
array_push($insertdata, $items);
}
$this->db->insert_batch('skillreqdept',$insertdata);
}
Ya, it should be empty. Check your array "
public function addItem(){
$data = array(
'item_ID"=>$_POST['item_ID'], <== wrong wrapping
'itemName"=>$_POST['itemName'],
'itemDescription"=>$_POST['itemDescription'],
'itemLink"=>$_POST['itemLink']
);
$orgID = $this->model->get_org();
$this->model->insertItem($data,$orgID);
}
If you're using proper IDE, it will highlight such a minor issues like this
As well insertdata is any predefined PHP tag/function ??
As well what is this null[$i] assign. I never heard of it.
Before do insert use print_r to check data is in the correct format or not. print_r($insertdata); die;
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
i have a joomla component for making appointments and i have checkboxes for starting dates of the appointments...my problem is that i can only make one appointment at a time,i want to be able to check multiple boxes so the values for those boxes can be saved in mysql,when i check multiple checkboxes only the last checked is saved in database...
here is the code from joomla component that i think that has to be adjusted so help guys if you can...
this is the code for checkbox...
$timetableHTML .= '<td class="timeSlot timeFree" ><input type="checkbox" name="appointment[]" value="'.$startKey.'" onclick="changeTimes(\''.$calendar->min_duration.'\',\''.$startKey.'\',\''.$endKey.'\')"/></td>';
and this is the save function in controller of the component...
function save() {
global $app;
JRequest::checkToken() or jexit( 'Invalid Token' );
$db =& JFactory::getDBO();
$row =& JTable::getInstance('appointments', 'Table');
$post = JRequest::get( 'post',4 );
if (!$row->bind( $post )) { JError::raiseError(500, $row->getError() ); }
for ($i=1;$i<=10;$i++) {
if (is_array($row->{'field'.$i})) $row->{'field'.$i} = implode('|',$row->{'field'.$i}); $row->{'field'.$i} = strip_tags($row->{'field'.$i});
}
if (!$row->check()) { JError::raiseError(500, $row->getError() ); }
if (!$row->store()) { JError::raiseError(500, $row->getError() ); }
$row->checkin();
if ($this->config->emails){
$this->notifyOwner(array($row->id));
$this->notifyAppointee(array($row->id));
}
$url = JRoute::_('index.php?option=com_jxtcappbook'.(JRequest::getInt( 'pop', 0) ? '&view=complete&tmpl=component' : ''));
$this->setRedirect($url ,JText::_( 'Termin je zakazan!'.$pop ));
}
i googled a bit and i think i need to set jrequest::get with array,am i right?
Assuming Joomla >1.6. Since you use JRequest a fair amount:
$appointments = JRequest::getVar('appointments', null, 'post', 'array');
or better yet since this will be deprecated post 3.0 you can use JInput:
$jinput = JFactory::getApplication()->input;
$appointments = $jinput->post->get('appointments', 'null', 'ARRAY');
Sanitize input and add to DB:
foreach (array_keys($appointments ) as $element) {
$myappointments[] = $db->quote($element);
}
// construct query using implode and use comma separator
$myappointments = implode(',', $myappointments );
$db =& JFactory::getDBO();
$query = $db->getQuery(true);
$query = sprintf('UPDATE $db->quoteName(#__mytable) SET $db->quote(...) WHERE $db->quote(...) IN (%s)', $myappointments );
$db->setQuery($query);
$db->query();
You get the idea...
EDIT (based on your comment):
I still don't know what you are trying to achieve. So it is hard for me to provide direction. I'll take another stab at it. I'm guessing you want to take the values that are checked from the form and put that into the database.
//this pulls out the values in an array of all the things that have been "checked" (selected in the checkbox)
$jinput = JFactory::getApplication()->input;
$appointments = $jinput->post->get('appointments', 'null', 'ARRAY');
//**This is not code you need** I just want to illustrate what you are getting.
//This is looping through the values of the checkboxes to see what you have
for($i=0; $i < count($appointments); $i++){
echo "Selected " . $appointments[$i];
}
The code I provided before shows you how to take the values and store into a DB. I can't give instructions on the DB because I don't know the DB structure.