here I save data to the database with multiple rows, I want to retrieve each last id per row, how do I do that?
ex : print_r result when input data.
Array
(
[0] => Array
(
[name] => metode 11
[description] => DESC 1
)
[1] => Array
(
[name] => metode 22
[description] => DESC 2
)
[2] => Array
(
[name] => metode 33
[description] => DESC 1
)
)
in database
id | name | description
1 metode 11 desc 1
2 metode 22 desc 2
3 metode 33 desc 3
after finished input I want to take each id
and this my code
$data = array();
$numrow = 1;
foreach ($sheet as $row) {
if ($numrow > 1) {
array_push($data, array(
'name' => $row['A'],
'description' => $row['B'],
));
}
$numrow++;
}
$this->db->insert_batch('my_tabel', $data);
$myid =$this->db->insert_id();
//after insert i retrieve id using last_id() function, however, only last id is fetched, i want to fetch each id
$data_1 = array();
$numrow2 = 1;
foreach ($sheet as $row) {
if ($numrow2 > 1) {
array_push($data_1, array(
'id_last' => $myid,
'id' => $row['E'],
'barang' => $row['F'],
));
}
$numrow2++;
}
i want like this :
Array
(
[0] => Array
(
[last_id] => 1
[id] => 33
[barang] => ccc
)
[1] => Array
(
[last_id] => 2
[id] => 44
[barang] => dd
)
[2] => Array
(
[last_id] => 3
[id] => 55
[barang] => eee
)
)
thanks in advance for those who have answered
I hope what I said was clear enough
Why not insert it row by row instead of a batch?
Build a dictionary from each insert to pair it back later on.
$data = array();
$numrow = 1;
foreach ($sheet as $row) {
if ($numrow > 1) {
array_push($data, array(
'name' => $row['A'],
'description' => $row['B'],
));
}
$numrow++;
}
$array_of_insert_id = array();
foreach ($data as $index => $data_to_insert) {
$this->db->insert('my_tabel', $data_to_insert);
$array_of_insert_id[$index] = $this->db->insert_id();
}
$data_1 = array();
$numrow2 = 1;
$counter = 0;
foreach ($sheet as $row) {
if ($numrow2 > 1) {
array_push($data_1, array(
'id_last' => $array_of_insert_id[$counter],
'id' => $row['E'],
'barang' => $row['F'],
));
}
$numrow2++;
$counter++;
}
//table field with input field data array
$table_data = [
'table_field1' => $input_data1,
'table_field2' => $input_data2,
];
//insert data in database
$this->db->insert('table_name',$table_data);
//after insert return id
return $inserted_id = $this->db->insert_id();
Related
I'm trying to batch update a table by an ID
My controller:
if(customCompute($this->data['student'])) {
$studentextendID = $this->data['student']->studentextendID;
$this->data['students'] = $this->studentextend_m->get_studentextend(array('studentextendID' => $studentextendID));
} else {
$this->data['students'] = [];
}
$post = $this->input->post();
for($i=0; $i < count($post['subject']); $i++) {
$studentExtendArray[] = array(
'studentextendID' => $studentextendID,
'studentID' => $studentID,
'subject' => $post['subject'][$i],
'subjectng' => $post['subjectng'][$i],
'subjectlg' => $post['subjectlg'][$i],
'subjectcre' => $post['subjectcre'][$i],
);
$this->db->update_batch('studentextend', $studentExtendArray, 'studentextendID');
}
My Model
function get_studentextend($array=NULL, $signal=FALSE) {
$query = parent::get($array, $signal);
return $query;
}
Array Output:
Array (
[0] => Array
(
[studentextendID] => 143
[studentID] => 97
[subject] =>
[subjectng] => 5235
[subjectlg] => 5231
[subjectcre] => 523155
)
[1] => Array
(
[studentextendID] => 143
[studentID] => 97
[subject] =>
[subjectng] => 2
[subjectlg] => 99
[subjectcre] => 3
) )
As you can see, 'studentextendID' is duplicated on both arrays, when it should be dynamically obtained, for example: 143 and 144, because there are two rows in the table with the same 'studentID'
You can try with change in model
public function update_batchs($table, $data)
{
if ($data) {
return $this->db->update_batch($table, $data, 'studentextendID');
}
}
You are not pass the $studentextendID in for loop.You need to pass this in for loop.
$studentextendID = $this->data['student']->studentextendID;
And also please verify $this->data['student'].
I have an array like this
Array
(
[0] => Array
(
[GRN_id] => 1
[flag_status] => 1
[array_indv_count] => 0
[qty] => 1
[location_RejHoldCmt] =>
[user_id] => 5
[date] => 29-Jul-2020
)
[1] => Array
(
[GRN_id] => 1
[flag_status] => 1
[array_indv_count] => 1
[qty] =>
[location_RejHoldCmt] =>
[user_id] => 5
[date] => 29-Jul-2020
)
[2] => Array
(
[GRN_id] => 2
[flag_status] => 3
[array_indv_count] => 2
[qty] => 0
[location_RejHoldCmt] =>
[user_id] => 5
[date] => 29-Jul-2020
)
)
This array is passing to the controller for insertion/updation:
$count = count($_POST['flag_status']);
for($i=0; $i < $count; $i++) {
$data[] = array(
'GRN_id'=>$_POST['id'],
'flag_status' => $_POST['flag_status'][$i],
'array_indv_count' => $i,
'qty' => $_POST['qty'][$i],
'location_RejHoldCmt' => $_POST['location_RejHoldCmt'][$i],
'user_id'=>$this->session->userdata('userid'),
'date'=>date('d-M-Y'),
);
}
$this->db->insert_batch('GRN_details', $data);
I need to update the DB if the rows exists in the array based on the three values(GRN_id,flag_status,array_indv_count) and insert if no matches with the same three values. Now the rows are inserting into the db on every execution. My DB structure is like below:
Instead of inserting as a batch, check for each record if it exists according to the conditions. If a record exists according to the conditions update that record else insert as a new record.
$count = count($_POST['flag_status']);
for($i=0; $i < $count; $i++) {
$data = array(
'GRN_id'=>$_POST['id'],
'flag_status' => $_POST['flag_status'][$i],
'array_indv_count' => $i,
'qty' => $_POST['qty'][$i],
'location_RejHoldCmt' => $_POST['location_RejHoldCmt'][$i],
'user_id'=>$this->session->userdata('userid'),
'date'=>date('d-M-Y'),
);
$data = xss_clean($data);
// select from table with conditions
$this->db->select('id')
$this->db->from('GRN_details')
$this->db->where('GRN_id', $data['GRN_id']);
$this->db->where('flag_status', $data['flag_status']);
$this->db->where('array_indv_count', $data['array_indv_count']);
$query = $this->db->get();
if ($query->num_rows() > 0) {
// if there is a match update
$record = $query->row();
$this->db->update('GRN_details', $data, array('id'=> $record->id ));
} else {
// if there is no match insert
$this->db->insert('GRN_details', $data);
}
}
I have this array:
Array (
[0] => Array
(
[0] => 2
)
[1] => Array
(
[0] => 2015-07-20
)
[2] => Array
(
[0] => 2
[1] => 5
)
[3] => Array
(
[0] => 70
[1] => 17
)
[4] => Array
(
[0] => 4
[1] =>
)
[5] => Array
(
[0] => 66
[1] => 17
)
)
Now I want Update to database like this
Array
(
[0] => Array
(
[0] => 2
[1] => 2015-07-20
[2] => 2
[3] => 70
[4] => 4
[5] => 66
)
[1] => Array
(
[0] => 2
[1] => 2015-07-20
[2] => 5
[3] => 17
[4] =>
[5] => 17
)
)
Is it possible? Or qny other way to UPdate record from array?
I have foreach loop OUTPUT like this:-
UPDATE update_shopwise_stock SET shop_id =2 datetime =2015-07-20 item_id =2 item_id =5 before_sale_totitem_qty =70 before_sale_totitem_qty =17 after_sale_totitem_qty =4 after_sale_totitem_qty = restOfItem =66 restOfItem =17 note =NULL WHERE shop_id =2
But I Want to this:-
UPDATE update_shopwise_stock SET shop_id =2 datetime =2015-07-20 item_id =2 before_sale_totitem_qty =70 after_sale_totitem_qty =4 restOfItem =66 note =NULL WHERE shop_id =2
UPDATE update_shopwise_stock SET shop_id =2 datetime =2015-07-20 item_id =5 before_sale_totitem_qty =17 after_sale_totitem_qty = restOfItem =17 note =NULL WHERE shop_id =2
Any help?
If i understand your question you need transform data from first array to second array and after you can make this foreach?
If yes there is transform to array with default values from 0 index. Works for multiple versions so you can add index 3,5, etc. and it will works still.
$default = array();
$versions = array();
foreach($array as $key => $values){
foreach($values as $version => $value){
if($version === 0){
$default[$key] = $value;
continue;
}
if(!array_key_exists($version, $versions)){
}
$versions[$version][$key] = $value;
}
}
$return = array(
0 => $default,
);
foreach($versions as $version => $versionData){
$return[$version] = $versionData+$default;
}
If you need foreach to build your SQL query it is here to:
$columns = array(
'shop_id', 'datetime', 'item_id', 'before_sale_totitem_qty', 'after_sale_totitem_qty', 'restOfItem'
);
foreach($return as $version => $data){
$columnData = array();
foreach($data as $columnIndex => $value){
$columnData[] = sprintf('%s = %s', $columns[$columnIndex], $value);
}
$sql = sprintf('UPDATE update_shopwise_stock SET %s WHERE shop_id=%d', implode(', ', $columnData), $data[0]);
}
But my personal recommendation is not use sql like this, but use PDO for prepare statement and better security. For prepare statement is for loop here:
$columns = array(
'shop_id', 'datetime', 'item_id', 'before_sale_totitem_qty', 'after_sale_totitem_qty', 'restOfItem'
);
foreach($return as $version => $data){
$columnPrepare = array();
$columnData = array();
foreach($data as $columnIndex => $value){
$columnName = $columns[$columnIndex];
$columnPrepare[] = sprintf('%s = :%s', $columnName, $columnName);
$columnData[$columnName] = $value;
}
$query = $db->prepare(sprintf("UPDATE update_shopwise_stock SET %s WHERE shop_id=:shop_id", implode(', ', $columnPrepare)));
foreach($columnData as $column => $value){
$query->bindParam(sprintf(':%s', $column), $value);
}
$query->execute();
}
Everything is untested and can have some bugs, eventually performance issue. It is based on question issue and show only way how to solve this issue.
I have the following db table
82 is the parent of 84. 24 is the parent of 82 and 83. In php I have a method to fetch rows by uid.
public function fetchByUid($uid){
//code
}
This would retrieve the 7th and 6th value from the table. Now I want to fetch not only the rows where uid is equal but also the rows where the parent is the child of uid. E.g. 82 is a parent of 84 but also a child of 24.
So I came up with some recursion.
public function fetchByUidRec($uid, $data, $counter){
//set of rows by uid
$db_resultSet;
foreach($db_resultSet as $row){
$entry = array();
$entry['id'] = $row->id;
$entry['uid'] = $row->uid;
$entry['rid'] = $row->rid;
$entry['layer'] = $counter;
$data [] = $entry;
//now I want to do the same on the child
$data [] = fetchByUidRec($row->rid, $data, $counter = $counter + 1)
}
return $data;
}
public function getchByUid($uid){
$data = array();
$counter = 0;
return fetchByUidRec($uid, $data, $counter)
}
But that does not work at all :( I want to store the current recrusion depth in $data['layer']
Any ideas?
If I understood you correctly:
$rows = array
(
0 => array('id' => 8, 'uid' => 82, 'rid' => 84),
1 => array('id' => 7, 'uid' => 24, 'rid' => 82),
2 => array('id' => 6, 'uid' => 24, 'rid' => 83),
);
function fetchByUidRec($uid, $counter = 0)
{
global $rows;
// or in your case
// $rows = SELECT FROM table WHERE uid = $uid;
$data = array();
foreach ($rows as $row)
{
if ($row['uid'] == $uid)
{
$data[] = array_merge($row, array('layer' => $counter));
$data = array_merge($data, fetchByUidRec($row['rid'], $counter++));
}
}
return $data;
}
Example:
echo '<pre>';
print_r(fetchByUidRec(24));
echo '</pre>';
Output:
Array
(
[0] => Array
(
[id] => 7
[uid] => 24
[rid] => 82
[layer] => 0
)
[1] => Array
(
[id] => 8
[uid] => 82
[rid] => 84
[layer] => 0
)
[2] => Array
(
[id] => 6
[uid] => 24
[rid] => 83
[layer] => 1
)
)
Considering this array
Array
(
[0] => Array
(
[id] => 51
[category_id] => 37
[title] => Sims
)
[1] => Array
(
[id] => 37
[category_id] => 26
[title] => Blackberry
)
[2] => Array
(
[id] => 26
[category_id] => 0
[title] => Mobile Device
)
I would like to be able to print out:
Mobile Device > Blackberry > Sims
Based on the relationship between category_id and id.
Can you use the id as the key into the array? It will make your life a bit simpler. For example, if you define your array:
Array
(
[51] => Array
(
[id] => 51
[category_id] => 37
[title] => Sims
)
[37] => Array
(
[id] => 37
[category_id] => 26
[title] => Blackberry
)
[27] => Array
(
[id] => 26
[category_id] => 0
[title] => Mobile Device
)
Then you can write code like:
//assume $a is your array, defined above
//and that you have used the id for the array key
$id = 51
do {
print $a['title'];
$id = $a['category_id'];
}while($id != 0);
EDIT: array_multisort probably isn't cleanest way to do this.
<?php
$array = Array(
array('id' => 51, 'category_id' => 37, 'title' => 'Sims'),
array('id' => 37, 'category_id' => 26, 'title' => 'Blackberry'),
array('id' => 26, 'category_id' => 0, 'title' => 'Mobile Device'));
// First build an associative array ID->Object
$map = array();
foreach( $array as $value )
{
$map[$value['id']] = $value;
}
// Then build your path
$path = array();
$value = $array[0];
while( true )
{
$path[] = $value['title'];
if( $value['category_id'] == 0 )
{
break;
}
$value = $map[$value['category_id']];
if( !isset($value) )
{
die("Data Inconsistency");
}
}
// Display path
echo implode(array_reverse($path), ' > ');
?>
Try array_multisort()
Does your original array also contains entries that are to be left out?
If not, use this:
$sort_array = array();
foreach ($original_array as $key => $value) {
$sort_array[] = $value['category_id'];
}
array_multisort($sort_array, SORT_ASC, $original_array);
The above will sort $original_array based on the category_id index.
If your array contains entries that have nothing to do with the rest, and you want to leave them out, you have to use something like this:
// remap keys based on category_id
$parts = array();
foreach ($original_array as $array) {
$parts[$array['category_id']] = $array;
}
// build tree list
$category_id = 0;
$result = array();
while (isset($parts[$category_id])) {
$result[] = $parts[$category_id]['title'];
$category_id = $parts[$category_id]['id'];
}
echo implode(' > ', $result);