Execute multi update array Code Igniter - php

I have a db table (form table for commercial propose) , the table is already filed with default rows, I want to execute multiple update query to change default values to the inserted values from from submit with post method in code igniter.. I have built a function save_report().
I have tried to use $this->db->update_batch(); , its only perform for the first foreach loop ..
function save_report(){
$data['old_circle'] = $this->input->post('old_circle');
$data['sold'] = $this->input->post('sold');
$data['diffrent_come'] = $this->input->post('diffrent_come');
$data['total'] = $this->input->post('total');
$data['new_circle'] = $this->input->post('new_circle');
$data['sold_start_month'] = $this->input->post('sold_start_month');
$data['bought_start_month'] = $this->input->post('bought_start_month');
$data['paid_start_month'] = $this->input->post('paid_start_month');
foreach($data as $key=>$value){
$comp = array('sold_start_month','bought_start_month','paid_start_month');
if(in_array($key,$comp)){
$this->db->where(array('report_id'=>1,'name' =>$key));
$this->db->update('reports_det',array('value'=>$value));
}
$update_array[] = array(
'name' =>$key,
'recived' =>$value['recived'],
'paid' =>$value['paid'],
'recived_bill'=>$value['recived_bill'],
'paid_bill' =>$value['paid_bill']
);
$this->db->where(array('report_id'=>1));
$this->db->update_batch('reports_det',$update_array,'name');
}
redirect('c_panel/reports_det_mangment/1');
}
thanks a lot ..

sorry guys for wasting your time , yesterday i was unfocused during work so today am really focus haha, the problem was i did not set foreach loop for every post array the final answer is here :
function save_report(){
$report_id = $this->input->post('rid');
if(count($_POST) > 0){
$data['old_circle'] = $this->input->post('old_circle');
$data['sold'] = $this->input->post('sold');
$data['diffrent_come'] = $this->input->post('diffrent_come');
$data['total'] = $this->input->post('total');
$data['new_circle'] = $this->input->post('new_circle');
$data['sold_start_month'] = $this->input->post('sold_start_month');
$data['bought_start_month'] = $this->input->post('bought_start_month');
$data['paid_start_month'] = $this->input->post('paid_start_month');
foreach($data['old_circle'] as $key=>$value){
$this->db->where(array('report_id'=>$report_id,'name' =>'old_circle'));
$this->db->update('reports_det',array($key=>$value));
}
foreach($data['sold'] as $key=>$value){
$this->db->where(array('report_id'=>$report_id,'name' =>'sold'));
$this->db->update('reports_det',array($key=>$value));
}
foreach($data['diffrent_come'] as $key=>$value){
$this->db->where(array('report_id'=>$report_id,'name' =>'diffrent_come'));
$this->db->update('reports_det',array($key=>$value));
}
foreach($data['total'] as $key=>$value){
$this->db->where(array('report_id'=>$report_id,'name' =>'total'));
$this->db->update('reports_det',array($key=>$value));
}
foreach($data['new_circle'] as $key=>$value){
$this->db->where(array('report_id'=>$report_id,'name' =>'new_circle'));
$this->db->update('reports_det',array($key=>$value));
}
foreach($data['sold_start_month'] as $value){
$this->db->where(array('report_id'=>$report_id,'name' =>'sold_start_month'));
$this->db->update('reports_det',array('value'=>$value));
}
foreach($data['bought_start_month'] as $value){
$this->db->where(array('report_id'=>$report_id,'name' =>'bought_start_month'));
$this->db->update('reports_det',array('value'=>$value));
}
foreach($data['paid_start_month'] as $value){
$this->db->where(array('report_id'=>$report_id,'name' =>'paid_start_month'));
$this->db->update('reports_det',array('value'=>$value));
}
}
redirect('c_panel/reports_det_mangment/'.$report_id);
}

Related

ON DUPLICATE KEY UPDATE [duplicate]

I have a CodeIgniter/PHP Model and I want to insert some data into the database.
However, I have this set in my 'raw' SQL query:
ON DUPLICATE KEY UPDATE duplicate=duplicate+1
I am using CodeIgniter and am converting all my previous in-controller SQL queries to ActiveRecord. Is there any way to do this from within the ActiveRecord-based model?
Thanks!
Jack
You can add the "ON DUPLICATE" statement without modifying any core files.
$sql = $this->db->insert_string('table', $data) . ' ON DUPLICATE KEY UPDATE duplicate=LAST_INSERT_ID(duplicate)';
$this->db->query($sql);
$id = $this->db->insert_id();
I hope it's gonna help someone.
The below process work for me in Codeigniter 3.0.6
public function updateOnDuplicate($table, $data ) {
if (empty($table) || empty($data)) return false;
$duplicate_data = array();
foreach($data AS $key => $value) {
$duplicate_data[] = sprintf("%s='%s'", $key, $value);
}
$sql = sprintf("%s ON DUPLICATE KEY UPDATE %s", $this->db->insert_string($table, $data), implode(',', $duplicate_data));
$this->db->query($sql);
return $this->db->insert_id();
}
Following the snippet linked by Pickett, I made a few modifications to:
1) Update it to use the new Query Builder (CI 3), formerly known as Active Record.
2) You can now pass an associative array (key => value) or an array of associative arrays. In the second form, it performs a multi-update.
I only tested it with mysqli, and it works well.
This piece of code goes in system/database/drivers/mysqli/mysqli_driver.php
function _duplicate_insert($table, $values)
{
$updatestr = array();
$keystr = array();
$valstr = array();
foreach($values as $key => $val)
{
$updatestr[] = $key." = ".$val;
$keystr[] = $key;
$valstr[] = $val;
}
$sql = "INSERT INTO ".$table." (".implode(', ',$keystr).") ";
$sql .= "VALUES (".implode(', ',$valstr).") ";
$sql .= "ON DUPLICATE KEY UPDATE ".implode(', ',$updatestr);
return $sql;
}
function _multi_duplicate_insert($table, $values)
{
$updatestr = array();
$keystr = array();
$valstr = null;
$entries = array();
$temp = array_keys($values);
$first = $values[$temp[0]];
foreach($first as $key => $val)
{
$updatestr[] = $key." = VALUES(".$key.")";
$keystr[] = $key;
}
foreach($values as $entry)
{
$valstr = array();
foreach($entry as $key => $val)
{
$valstr[] = $val;
}
$entries[] = '('.implode(', ', $valstr).')';
}
$sql = "INSERT INTO ".$table." (".implode(', ',$keystr).") ";
$sql .= "VALUES ".implode(', ',$entries);
$sql .= "ON DUPLICATE KEY UPDATE ".implode(', ',$updatestr);
return $sql;
}
And this goes into the /system/database/DB_query_builder.php file:
function on_duplicate($table = '', $set = NULL )
{
if ( ! is_null($set))
{
$this->set($set);
}
if (count($this->qb_set) == 0)
{
if ($this->db_debug)
{
return $this->display_error('db_must_use_set');
}
return FALSE;
}
if ($table == '')
{
if ( ! isset($this->qb_from[0]))
{
if ($this->db_debug)
{
return $this->display_error('db_must_set_table');
}
return FALSE;
}
$table = $this->qb_from[0];
}
$is_multi = false;
foreach (array_keys($set) as $k => $v) {
if ($k === $v) {
$is_multi = true; //is not assoc
break;
}
}
if($is_multi)
{
$sql = $this->_multi_duplicate_insert($this->protect_identifiers($table, TRUE, NULL, FALSE), $this->qb_set );
}
else
{
$sql = $this->_duplicate_insert($this->protect_identifiers($table, TRUE, NULL, FALSE), $this->qb_set );
}
$this->_reset_write();
return $this->query($sql);
}
Then you can do this for a single row insert/update:
$this->db->on_duplicate('table', array('column1' => 'value', 'column2' => 'value'));
Or this for a multi insert/update:
$this->db->on_duplicate('table', array(
array('column1' => 'value', 'column2' => 'value'),
array('column1' => 'value', 'column2' => 'value')
));
You can tweak the active record function with minimal addition:
DB_driver.php add inside the class:
protected $OnlyReturnQuery = false;
public function onlyReturnQuery($return = true)
{
$this->OnlyReturnQuery = $return;
}
find function query( ...and add at the very beginning:
if ($this->OnlyReturnQuery) {
$this->OnlyReturnQuery = false;
return $sql;
}
and finally in DB_active_rec.php add function:
public function insert_or_update($table='', $data=array())
{
$this->onlyReturnQuery();
$this->set($data);
$insert = $this->insert($table);
$this->onlyReturnQuery();
$this->set($data);
$update = $this->update($table);
$update = preg_replace('/UPDATE.*?SET/',' ON DUPLICATE KEY UPDATE',$update);
return $this->query($insert.$update);
}
Now you can use it as:
$this->db->insert_or_update('table',array $data);
Pros:
uses all the active record validation
Cons:
it is not the best (the most proper) way of extending the function, because if you are planning to update these files, you will have to redo the procedure.
The link to the forum thread above is broken. I don't know of a better way than just using db->query for the call, if someone has a better solution, please post that.
$result = $this->CI->db->query(
"INSERT INTO tablename (id, name, duplicate) VALUES (1, 'Joe', 1) ".
"ON DUPLICATE KEY UPDATE duplicate=duplicate+1");
I hope this helps someone looking for a solution to this.
Below is a code snippet I use everytime for update on duplicates:
$sql = "insert into table_name (id, name) values(".$id.",'".$name."') on duplicate key update id=".$id.",name='".$name."'";
//Executing queries
$result = $this->db->query($sql, array($id, $name));
Note: column id must be primary or unique
Using $this->db->query() and parameters, this is how I do it. the first 4 parameters are for the insert part and the last three parameters are repeated for the on duplicate key update part.
$sql = "insert into application_committee ".
"(application_id, member1_id, member2_id, member3_id) values (?, ?, ?, ?)".
" on duplicate key update member1_id = ?, member2_id = ?, member3_id = ?";
$this->db->query($sql, array($appid, $member_1, $member_2, $member_3,
$member_1, $member_2, $member_3);
Simply done -
$updt_str = '';
foreach ($insert_array as $k => $v) {
$updt_str = $updt_str.' '.$k.' = '.$v.',';
}
$updt_str = substr_replace($updt_str,";", -1);
$this->db->query($this->db->insert_string('table_name', $insert_array).' ON DUPLICATE KEY UPDATE '.$updt_str);

codeigniter: alteration of PHP array

i am sending $_POST['checkbox_name'] to function insert_to_table.
function insert_to_table($valid_array)
{
$data_array = array();
$this->load->model('get_data_model');
$updated_max_brand_id = $this->get_data_model->get_max_brand_id();
foreach ($valid_array as $key => $value) {
$data_array['bdc_brand_id'] = $updated_max_brand_id;
$data_array['bdc_cat_id'] = $value;
}
$this->db->insert('mart_brand_dealing_cat',$data_array);
}
the final mysql query should run as below
INSERT INTO `mart_brand_dealing_cat` (`bdc_brand_id`, `bdc_cat_id`) VALUES (11,43),(11,42);
11 - updated_max_brand_id;
42,43 are coming from already existed array $valid_array.
I am trying to insert multiple values at a time.How can i do it. i may wrong please guide and help me.
Your probably looking for something like $this->db->insert_batch();
So for example:
<?php
function insert_to_table($valid_array)
{
$this->load->model('get_data_model');
$brand_id = $this->get_data_model->get_max_brand_id();
$insert = array();
foreach ($valid_array as $key => $cat_id) {
$insert[] = array(
'bdc_brand_id' => $brand_id,
'bdc_cat_id' => $cat_id,
);
}
if (!empty($insert)) {
return $this->db->insert_batch('mart_brand_dealing_cat', $insert);
} else {
return false;
}
}
?>

Create array nested PHP

Hi all' I have a page into PHP where I retrieve XML data from a server and I want to store this data into an array.
This is my code:
foreach ($xml->DATA as $entry){
foreach ($entry->HOTEL_DATA as $entry2){
$id = (string)$entry2->attributes()->HOTEL_CODE;
$hotel_array2 = array();
$hotel_array2['id'] = $entry2->ID;
$hotel_array2['name'] = utf8_decode($entry2->HOTEL_NAME);
$i=0;
foreach($entry2->ROOM_DATA as $room){
$room_array = array();
$room_array['id'] = (string)$room->attributes()->CCHARGES_CODE;
$hotel_array2['rooms'][$i] = array($room_array);
$i++;
}
array_push($hotel_array, $hotel_array2);
}
}
In this mode I have the array hotel_array which all hotel with rooms.
The problem is that: into my XML I can have multiple hotel with same ID (the same hotel) with same information but different rooms.
If I have an hotel that I have already inserted into my hotel_array I don't want to insert a new array inside it but I only want to take its rooms array and insert into the exisiting hotel.
Example now my situation is that:
hotel_array{
[0]{
id = 1,
name = 'test'
rooms{
id = 1
}
}
[0]{
id = 2,
name = 'test2'
rooms{
id = 100
}
}
[0]{
id = 1,
name = 'test'
rooms{
id = 30
}
}
}
I'd like to have this result instead:
hotel_array{
[0]{
id = 1,
name = 'test'
rooms{
[0]{
id = 1
}
[1]{
id = 30
}
}
}
[0]{
id = 2,
name = 'test2'
rooms{
id = 100
}
}
}
How to create an array like this?
Thanks
first thing is it helps to keep the hotel id as the index on hotel_array when your creating it.
foreach ($xml->DATA as $entry){
foreach ($entry->HOTEL_DATA as $entry2){
$id = (string)$entry2->attributes()->HOTEL_CODE;
$hotel_array2 = array();
$hotel_array2['id'] = $entry2->ID;
$hotel_array2['name'] = utf8_decode($entry2->HOTEL_NAME);
$i=0;
foreach($entry2->ROOM_DATA as $room){
$room_array = array();
$room_array['id'] = (string)$room->attributes()->CCHARGES_CODE;
$hotel_array2['rooms'][$i] = array($room_array);
$i++;
}
if (!isset($hotel_array[$hotel_array2['id']])) {
$hotel_array[$hotel_array2['id']] = $hotel_array2;
} else {
$hotel_array[$hotel_array2['id']]['rooms'] = array_merge($hotel_array[$hotel_array2['id']]['rooms'], $hotel_array2['rooms']);
}
}
}
Whilst this is the similar answer to DevZer0 (+1), there is also quite a bit that can be done to simplify your workings... there is no need to use array_merge for one, or be specific about $i within your rooms array.
$hotels = array();
foreach ($xml->DATA as $entry){
foreach ($entry->HOTEL_DATA as $entry2){
$id = (string) $entry2->attributes()->HOTEL_CODE;
if ( empty($hotels[$id]) ) {
$hotels[$id] = array(
'id' => $id,
'name' => utf8_decode($entry2->HOTEL_NAME),
'rooms' => array(),
);
}
foreach($entry2->ROOM_DATA as $room){
$hotels[$id]['rooms'][] = array(
'id' => (string) $room->attributes()->CCHARGES_CODE;
);
}
}
}
Just in case it helps...
And this :)
$hotel_array = array();
foreach ($xml->DATA as $entry)
{
foreach ($entry->HOTEL_DATA as $entry2)
{
$hotel_code = (string) $entry2->attributes()->HOTEL_CODE;
if (false === isset($hotel_array[$hotel_code]))
{
$hotel = array(
'id' => $entry2->ID,
'code' => $hotel_code,
'name' => utf8_decode($entry2->HOTEL_NAME)
);
foreach($entry2->ROOM_DATA as $room)
{
$hotel['rooms'][] = array(
'id' => (string)$room->attributes()->CCHARGES_CODE,
);
}
$hotel_array[$hotel_code] = $hotel;
}
}
}

how to update mysql table from Serialised json?

I have get Serialised from Nestable, but I don't know how to write php code update my database like wordpress:
$data = '[{"id":1},{"id":2,"children":[{"id":3},{"id":4},{"id":5,"children":[{"id":6},{"id":7},{"id":8}]},{"id":9},{"id":10}]},{"id":11},{"id":12}]';
function extract_value($value,$order=0){
if(is_array($value)){
foreach($value as $k => $v){
echo "UPDATE vod_page_menu SET ordering = '$order', parent_id = '$v' WHERE id = '$v'; <br/>";
extract_value($v,$order+1);
}
}
}
$json = json_decode($data,true);
extract_value($json);
You need to first decode the JSON, then you can use it in PHP:
$data = json_decode($data, true);
foreach ($data as $id => $value) {
...
}
function extract_value($array,$parent=0,$i=1){
foreach($array as $k => $v) {
$id = $array[$k]['id'];
echo "UPDATE vod_page_menu SET ordering = '$i', parent_id = '$parent' WHERE id = '$id'; <br/>";
if(isset($array[$k]['children'])){
$children = $array[$k]['children'];
foreach($children as $key => $obj){
$child = $children[$key]['id'];
$i++;
echo "UPDATE vod_page_menu SET ordering = '$i', parent_id = '$id' WHERE id = '$child'; <br/>";
if(isset($children[$key]['children']))
extract_value($children[$key]['children'],$child,++$i);
}
}
$i++;
}
}

comma separated list in php

I am trying to build a list separated by commas which should look like this (green, orange, red).
$i=0;
$taxonomy = $form_state[values][taxonomy][5];
foreach ($taxonomy as $key => $value){
$result = db_query("SQL CODE goes here");
if (mysql_num_rows($result)){
while ($i<mysql_num_rows($result)){
$resultset = db_fetch_array($result);
$comma_separated = implode(",", $resultset);
$i++;
}
form_set_error("Date", t("$comma_separated. cannot be booked more than once "));
}
$resultset=array();
while ($data = db_fetch_array($result)) {
$resultset[] = $data;
}
$comma_separated = implode(",", $resultset);
Someone posted it and I was going to upvote, but they removed it. I think mysql GROUP_CONCAT would be a good solution, since it looks like getting a comma separated list is the only purpose of this query.
Try this:
$i=0;
$taxonomy = $form_state[values][taxonomy][5];
$result='';
foreach ($taxonomy as $key => $value)
{
$result = db_query("SQL CODE goes here");
if (mysql_num_rows($result)){
while ($row = mysql_fetch_row()){
result.=$row[0].',';
}
}
}
result=substr($result,0,-1);
echo $result;

Categories