I am having a problem passing a variable to be saved as INT in MySQL. The closest thing I could find to my issue is this question but I have already verified that I am not using single and double quotes. When I print_r($this->session->userdata('subdomain')) I see the correct subdomain id on my screen (in this case 10), but when I try passing this using $params it always save subdomain_id as 0 and I can not figure out why.
Here is Project_assignees_model:
function add_prefix_project_assignees($params)
{
$this->db->insert('prefix_project_assignees',$params);
return $this->db->insert_id();
}
Here is my Project controller (Specifically it is the $assignees array):
function edit($entry_id)
{
$this->load->library('form_validation');
$this->form_validation->set_rules('client_id','Client Id','required|integer');
$this->form_validation->set_rules('title','Project Title','required|max_length[255]');
$this->form_validation->set_rules('project_status','Project Status','required');
$this->form_validation->set_rules('project_details','Project Details','required');
$this->form_validation->set_rules('project_estimated_hours','Project Estimated Hours','required|max_length[255]');
$this->form_validation->set_rules('end','Project Deadline','required');
if($this->form_validation->run())
{
date_default_timezone_set("America/New_York");
$date = date("Y-m-d h:i:sa");
$params = array(
'subdomain_id' => $this->session->userdata('subdomain'),
'client_id' => $this->input->post('client_id'),
'title' => $this->input->post('title'),
'project_status' => $this->input->post('project_status'),
'project_details' => $this->input->post('project_details'),
'project_last_updated' => $date,
'project_estimated_hours' => $this->input->post('project_estimated_hours'),
'start' => $this->input->post('start'),
'end' => $this->input->post('end'),
'owner_id' => get_current_user_id(),
);
$prefix_projects_id = $this->Project_model->update_prefix_projects($entry_id,$params);
$assignees = array(
'subdomain_id' => $this->session->userdata('subdomain'),
'project_id' => $entry_id,
'user_id' => $this->input->post('assignee'),
);
$this->load->model('Project_assignee_model');
$insertAssignees = array();
for ($i = 0; $i < count($assignees['user_id']); $i++)
{
//Get user_id from ID
$userID = $assignees['user_id'][$i];
$insertAssignees[$i] = array('project_id' => $entry_id, 'user_id' => $assignees['user_id'][$i]); // $insert is ready for insert_batch
$prefix_assignees = $this->Project_assignee_model->add_prefix_project_assignees($insertAssignees[$i]);
}
//redirect('project/index');
}
else
{
$this->load->model('Client_model');
$data['prefix_clients'] = $this->Client_model->get_all_prefix_clients();
$data['prefix_projects'] = $this->Project_model->get_prefix_projects($entry_id);
$data['prefix_users'] = $this->aauth->list_users();
$this->load->model('Project_assignee_model');
$data['prefix_assignees'] = $this->Project_assignee_model->get_prefix_project_assignees($entry_id);
$this->load->view('project/edit',$data);
}
}
Why does print_r show the correct subdomain_id but when it is saved to database it saves as 0?
*******UPDATE*******
Just for reference, this works:
$assignees = array(
'subdomain_id' => 10,
'project_id' => $entry_id,
'user_id' => $this->input->post('assignee'),
);
But this does not (Even though printing the userdata for subdomain gives me 10):
$assignees = array(
'subdomain_id' => $this->session->userdata('subdomain'),
'project_id' => $entry_id,
'user_id' => $this->input->post('assignee'),
);
Sometimes I guess it just takes writing it out for others before I realize my problem. When I loop through each assignee to add them to the table I realized I was not passing the subdomain_id with it.
I had this:
$insertAssignees[$i] = array('project_id' => $entry_id, 'user_id' => $assignees['user_id'][$i]); // $insert is ready for insert_batch
Needed to be changed to have subdomain_id included
$insertAssignees[$i] = array('subdomain_id' => $this->session->userdata('subdomain'), 'project_id' => $entry_id, 'user_id' => $assignees['user_id'][$i]); // $insert is ready for insert_batch
Related
I used CodeIgniter as a framework for my development.
I am trying to insert data to a table at MySQL database.
Data is inserted as follows.
$dataArray['categoryId'] = $categoryId['id'];
$dataArray['subCategoryId'] = $subTypeId;
$dataArray['title'] = $title;
$dataArray['regionId'] = $regionId;
$dataArray['slogan'] = $slogan;
$dataArray['lastUpdated'] = date('Y-m-d H:i:s');
$dataArray['createdDate'] = date('Y-m-d H:i:s');
$dataArray['state'] = 'Unhide';
$dataArray['status'] = 'Active';
$dataArray['approval'] = 'Incompleted';
$dataArray['user_id'] = $userId;
$this->db->insert($carrentals, $dataArray);
$insertId = $this->db->insert_id();
My table is structured as in the attached image.
$insertId always returns 0 and no data is inserted into the table.
I can manually insert data into the table.
What could be wrong?
I have AUTO_INCREMENT column as id. But no data is inserted and always returns 0.
EDIT:
My actual code is
$dataArray = [
'categoryId' => $categoryId['id'],
'subCategoryId' => $subTypeId,
'title' => $title,
'regionId' => $regionId,
'slogan' => $slogan,
'lastUpdated' =>date('Y-m-d H:i:s')
];
if (empty($_POST['referenceId'])) {
$dataArray['createdDate'] = date('Y-m-d H:i:s');
$dataArray['state'] = 'Unhide';
$dataArray['status'] = 'Active';
$dataArray['approval'] = 'Incompleted';
$dataArray['user_id'] = $userId;
$this->db->insert($carrentals, $dataArray);
$insertId = $this->db->insert_id();
$responseArray = array(
'result' => $insertId,
'success' => true);
return $this->set_response($responseArray, REST_Controller::HTTP_OK);
}
Probably returning FALSE not zero. insert() returns TRUE or FALSE, check the results before proceeding
$inserted = $this->db->insert($carrentals, $dataArray);
if($inserted)
{
$responseArray = ['result' => $insertId, 'success' => true];
}
else
{
$responseArray = ['result' => NULL, 'success' => false];
}
return $this->set_response($responseArray, REST_Controller::HTTP_OK);
I don't see any problem with the way you create $dataArray.
Try replacing your $dataArray for
$dataArray = array( 'categoryId' => $categoryId['id'],
'subCategoryId' => $subTypeId,
'title' => $title,
'regionId' => $regionId,
'slogan' => $slogan,
'lastUpdated' => date('Y-m-d H:i:s'),
'createdDate' => date('Y-m-d H:i:s'),
'state' => 'Unhide',
'status' => 'Active',
'approval' => 'Incompleted',
'user_id' => $userId
);
$this->db->insert($carrentals, $dataArray);
$insertId = $this->db->insert_id();
Try to checking how is the query with $this->db->last_query();, additionally check relations (if you have it), if userId or categoryId are empty.
-- https://www.codeigniter.com/user_guide/database/helpers.html
I am currently working on adding multiple requests in single click using CodeIgniters insert_batch.
This is my model
function add_request($data) {
$this->db->insert_batch('requests',$data);
}
This is my controller
if($_POST) {
$code = $this->input->post('code');
$about = $this->input->post('about');
$qnty = $this->input->post('quantity');
$budget = $this->input->post('budget');
$sched = $this->input->post('sched');
for($i = 0; $i < count($code); $i++) {
$data[$i] = array(
'code' => $code,
'description' => $_POST['desc'],
'qnty' => $qnty,
'budget' => $budget,
'sched' => $sched,
'from' => $this->session->userdata('user_id'),
'status' => 'Pending',
'about' => $about
);
$this->request->add_request($data[$i]);
}
This code doesnt work It only adds blank record.
Consider this code for the controller:
$data = array();
for($i = 0; $i < count($code); $i++) {//build the array
$data[$i] = array(
'code' => $code,
'description' => $_POST['desc'],
'qnty' => $qnty,
'budget' => $budget,
'sched' => $sched,
'from' => $this->session->userdata('user_id'),
'status' => 'Pending',
'about' => $about
);
}
//$data will be a bidimentional array
//pass $data to the model after the looping is done, thus the array is complete
$this->request->add_request($data);
I never used generators in PHP. I understand the way to use it :
Foreach an array to do some tasks for each value like greping a specific line into a big file to remove some caracteres..
What I need :
I need to retrieve all bands from my dabatase. Sure I have the 'limit' argument to don't exceed the PHP's memory (there're 30 000 bands..).
I have to filters values and return a new array to the client into my REST API.
What I want to know :
Is it interesting for me to create a method into a trait called 'generator' to perform the code bellow ?
In all cases, I have to create a new array to return it into my method
$bands = Models\Bands::find($bandsParameters);
$json = [];
foreach ($bands as $band) {
$followers = $band->getFollowers();
$followersArr = [];
foreach ($followers as $follower) {
$followerImage = $follower->getImage();
$followerObj = (object)[
'id' => $follower->id,
'username' => $follower->username,
'image' => $followerImage->url,
'online' => $follower->online,
'createdOn' => $follower->createdOn,
'updatedOn' => $follower->updatedOn,
'lastLogin' => $follower->lastLogin,
];
$followersArr[] = $followerObj;
}
$info = $band->getInfo($bandInfoParameters)->getFirst();
$bandObj = (object)[
'id' => $band->id,
'name' => $band->name,
'style' => $band->styles,
'country' => $band->country,
'summary' => isset($info->summary) ? $info->summary : null,
'followers' => $followersArr,
'createdOn' => $band->createdOn,
'updatedOn' => $band->updatedOn,
'authoredBy' => $band->authoredBy,
'updatedBy' => $band->updatedBy,
];
$json[] = $bandObj;
}
return ['key' => 'bands', 'value' => $json];
I want to insert data into my database. I am using codeigniter framework to build my app.
When I click on submit button,It don't give any error just reload the same page and data in not inserted in database.
Following my code to insert data into database -
public function addSale($saleDetails = array(), $items = array(), $warehouse_id)
{
foreach($items as $data){
$product_id = $data['product_id'];
$product_quantity = $data['quantity'];
$this->updateProductQuantity($product_id, $warehouse_id, $product_quantity);
}
// sale data
$saleData = array(
'reference_no' => $saleDetails['reference_no'],
'warehouse_id' => $warehouse_id,
'biller_id' => $saleDetails['biller_id'],
'biller_name' => $saleDetails['biller_name'],
'customer_id' => $saleDetails['customer_id'],
'customer_name' => $saleDetails['customer_name'],
'date' => $saleDetails['date'],
'note' => $saleDetails['note'],
'internal_note' => $saleDetails['internal_note'],
'inv_total' => $saleDetails['inv_total'],
'total_tax' => $saleDetails['total_tax'],
'total' => $saleDetails['total'],
'total_tax2' => $saleDetails['total_tax2'],
'tax_rate2_id' => $saleDetails['tax_rate2_id'],
'inv_discount' => $saleDetails['inv_discount'],
'discount_id' => $saleDetails['discount_id'],
'user' => $saleDetails['user'],
'shipping' => $saleDetails['shipping']
);
if($this->db->insert('sales', $saleData)) {
$sale_id = $this->db->insert_id();
$addOn = array('sale_id' => $sale_id);
end($addOn);
foreach ( $items as &$var ) {
$var = array_merge($addOn, $var);
}
if($this->db->insert_batch('sale_items', $items)) {
return true;
}
}
return false;
}
Based on https://ellislab.com/codeigniter/user-guide/database/examples.html , it seems to me, that you are missing a line -> $this->db->insert('sales', $saleData); . You do have it inside an if statement, but if statement will not execute it as a code, but check if it returns true.
$saleData = array(
'reference_no' => $saleDetails['reference_no'],
'warehouse_id' => $warehouse_id,
'biller_id' => $saleDetails['biller_id'],
'biller_name' => $saleDetails['biller_name'],
'customer_id' => $saleDetails['customer_id'],
'customer_name' => $saleDetails['customer_name'],
'date' => $saleDetails['date'],
'note' => $saleDetails['note'],
'internal_note' => $saleDetails['internal_note'],
'inv_total' => $saleDetails['inv_total'],
'total_tax' => $saleDetails['total_tax'],
'total' => $saleDetails['total'],
'total_tax2' => $saleDetails['total_tax2'],
'tax_rate2_id' => $saleDetails['tax_rate2_id'],
'inv_discount' => $saleDetails['inv_discount'],
'discount_id' => $saleDetails['discount_id'],
'user' => $saleDetails['user'],
'shipping' => $saleDetails['shipping']
);
$this->db->insert('sales', $saleData);
This should work. You can also check if it succeeds like this ->
return ($this->db->affected_rows() != 1) ? false : true;
first of, just wanted to let you know that I am a newbie at CI. but I am having trouble with this piece of code where is breaking and I can't seem to be able to find the answer anywhere.
for some reason the code is breaking at the first if statement.. if possible could you help me out understand what is really happening there?
Thank you all for your help!
function main
{
$this->load->model(getData) psudo code for this area...
}
---model---
function getData....
{
Sql = this->db->query(sql code that returns all the information required.)
$result = $sql->result_array();
$types = array ( 'EVENT|TIME' => array( 'id' => 1, 'name' => 'Regular' ),
'PROPOSITION|REGULAR' => array( 'id' => 2, 'name' =>'Propositions'),
'EVENT|TIME' => array( 'id' => 3, 'name' => 'Now' ),
'PROPOSITION|FUTURES' => array( 'id' => 4, 'name' => 'Future' ));
$var = array();
foreach ($result as $event) {
$cat = $event['type'] . '|' . $event['sub_type'];
$typeId = $types[$cat]['id'];
if(!is_array($var[$event['event_id']]['var'][$event['type_id']]))
{
if(!is_array($var[$event['event_id']]))
{
$var[$event['event_id']] = array( 'event_name' =>
$event['event_name'],'event_abbreviation' =>
$event['event_abbreviation']);
}
$var[$event['event_id']]['var'][$event['type_id']] = array(
'type_name' => $event['abbreviation'],'type_abbreviation' => $event['name']
);
}
$event[$event['event_id']]['var'][$event['type_id']]['types'][$typeId] =
$types[$cat]['name'];
}
return $myResults;
}
In this line
if(!is_array($var[$event['event_id']]['var']$event['type_id']]))
You are missing a [ somewhere. I'm guessing before $event['type_id'].
So replace with:
if(!is_array($var[$event['event_id']]['var'][$event['type_id']]))