"Batch Insert" inserts null value in database - 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;

Related

Redbean R::Find returns empty beans

using this:
$rdy = R::find( 'players','room=0');
$count = count($rdy);
if($count>1)
{
for($i=0;$i<$count;$i++)
{
$id = $rdy[$i]->id;
$user = R::load('players',$id);
if($user->id!=0)
{
//changing $user variables..
R::store($user);
}
}
}
but beans that R::find() function found give empty fields,
am i using it wrong?
Replace your first line
$rdy = R::find( 'players','room=0');
with
$rdy = R::find('players', " room = ?", [0]);
You can place variables instead of the hard coded 0.
You can also check on multiple properties and pass multiple variables in the array

zend update is deleting old values

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;
}

MySQL Update with field being a concatenated string

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!

Codeigniter Transaction inside Control

Since I have several functions executing in the following control as a single transaction I couldn't surround each function as a transaction in the model. So I did it the following way. Please someone let me know if there is any problem. Works fine for now, but have no idea whether it will get any concurrency issues or there is any other way?
if(isset($_POST['btnsave']))
{
$mcodes = $_POST['tblmcode'];
$count = count($mcodes);
//echo $count;
$issue = new Materialissue_model();
$this->db->trans_start(); //Here starts my transaction
$issue->setIssuecode($this->input->post('txtissuecode'));
if($issue->checkNoExistence()) {
$issue->setDate($this->input->post('txtdate'));
$issue->setCustomer($this->input->post('txtcustomer'));
$issue->setFromlocation($this->input->post('txtlocation'));
$issue->setResponsible($this->input->post('txtresponsible'));
$issue->setComments($this->input->post('txtcomments'));
$issue->setTotal($this->input->post('txttotal'));
$issue->setUser($this->session->userdata('username'));
$issue->setStatus($this->input->post('txtstatus'));
for ($i = 0; $i < $count; $i++) {
$issue->setMaterialcode($_POST['tblmcode'][$i]);
$issue->setMaterialname($_POST['tblmname'][$i]);
$issue->setCost($_POST['tblcost'][$i]);
$issue->setQty($_POST['tblqty'][$i]);
$issue->setSubtotal($_POST['tblsubtotal'][$i]);
$issue->saveIssueDetail();
$stock = new Materialstock_model();
$stock->setItemcode($_POST['tblmcode'][$i]);
$stock->setItemlocation($this->input->post('txtlocation'));
$stock->setQty($_POST['tblqty'][$i]);
$stock->setRefno($this->input->post('txtissuecode'));
$stock->setLasttransaction('MATERIAL-ISSUE');
$stock->updateMaterialIssueStock();
$transaction = new Transaction_model();
$transaction->setDescription("MATERIAL-ISSUE");
$transaction->setItemcode($_POST['tblmcode'][$i]);
$transaction->setRecqty("0");
$transaction->setTransqty("0");
$transaction->setIssueqty($_POST['tblqty'][$i]);
$transaction->setDate($this->input->post('txtdate'));
$transaction->setUser($this->session->userdata('username'));
$transaction->saveMaterialTransaction();
}
$result = $issue->saveIssue();
$this->db->trans_complete(); //Here ends my transaction
if ($result) {
$message = new Message_model();
$data['message'] = $message->recordadded;
$data['type'] = "success";
$data['returnpage'] = base_url() . "index.php/materialissue_control/show";
$data["print"] = base_url() . "index.php/Notegenerator_control/showMaterialIssueNote?code=".$issue->getIssuecode();
$this->load->view('messageprint_view', $data);
}
}else{
$message = new Message_model();
$data['message'] = $message->issuecodeexists;
$data['type'] = "error";
$data['returnpage'] = base_url() . "index.php/materialissue_control/show";
$this->load->view('message_view', $data);
}
}
I prefer like using trigger to handle many functions in one controller, this make mycode clean and easy to track. example:
user writes article, this action will call one action in model write_article combine with 1 transaction, but this function run any query :
1.insert post
2.lock count post category
3.lock count user post
4.lock count post by date
example in code
public function write_article($post) {
$this->cms->db->trans_start(TRUE);
$this->cms->db->set('content', $posts->get_content());
$this->cms->db->insert('t_posts');
$this->cms->db->trans_complete();
if($this->cms->db->trans_status() === TRUE){
$this->cms->db->trans_commit();
}else{
$this->cms->db->trans_rollback();
}
}
This reference about trigger
www.sitepoint.com/how-to-create-mysql-triggers

Inserting multiple checkbox values in mysql

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.

Categories