How to update a column in the database using SQL - php

I am having two tables, in one of the table I am inserting the data and in the other table I want to update a single column. But if I use update, it is updating all the columns in that table. It is inserting correctly. Can any one help me?
$this->db->trans_begin();
$data=array(
'company_name'=>$this->input->post('company_name'),
'category_id'=>$this->input->post('category_id'),
'quantity_rec'=>$this->input->post('quantity_rec'),
);
$this->db->insert('inventory',$data);
$a=$this->input->post('quantity_rec');
$b=$this->input->post('stock');
$c=$a+$b;
$data1=array(
'stock'=>$c,
);
$this->db->where(array('department_category.category_id'=>$id));
$this->db->update('department_category',$data1);
$this->db->trans_complete();
}

$this->db->update('department_category',$data1);
should have parameter where
$this->db->where(somewhere);
if no well, u change entire data dude

Related

Codeigniter : append record in mysqli

i want to update my column data in a way that posted data gets appended at the end of the existing column data. Current data is in Json format
This is how i am updating record
$data=array('services', $array );
$this->db->where('id',$id)
$this->db->update('garage',$data);
but this updates whole record how do i append the record at the end of json
You can select the data from the database and use PHP way to concatenate the string and run the update.
$d=$this->db->get_where('garage',array('id',$id))->row();
Now merge the you can merge the existing data with new data.
$new_data=$d->services.json_encode($array);
$data=array('services', $new_data );
$this->db->where('id',$id)
$this->db->update('garage',$data);
Hope this will fix the issue.

batch delete in codeigniter

insert_batch() is a codeigniter build-in function which inserts 100 data of rows at a time. That's why it is so much faster for inserting large amount of data.
Now I want to delete large number of data like insert_batch() function does.
Is their any way to do it?
Already I am using where_in function but it is not that much faster like insert_batch() and that's why timeout error occur often.
I want to know specially that can i make a function like insert_batch() or insert_update() in codeigniter system/database/db_query_builder ?
If I can how to do it. or any other suggestion please ?
If we are talking about alot of rows, it may be easier to perform a table 'switch' by inserting and dropping the the original table.
However one drawback to this will mean any Auto Increment IDs will be lost.
<?php
// Create a Copy of the Same Data structure
$this->db->query( "CREATE TABLE IF NOT EXISTS `TB_TMP` .. " );
// Select the data you wish to -Keep- by excluding the rows by some condition.
// E.g. Something that is no longer active.
$recordsToKeep =
$this->db
->select( "*" )
->get_where( "TB_LIVETABLE", [ "ACTIVE" => 1 ])
->result();
// Insert the Excluded Rows.
$this->db->insert_batch( "TB_TMP", $recordsToKeep );
// Perform the Switch
$this->db->query( "RENAME TABLE TB_LIVETABLE TO TB_OLDTABLE" );
$this->db->query( "RENAME TABLE TB_TMP TO TB_LIVETABLE " );
$this->db->query( "DROP TABLE TB_OLDTABLE" );

Laravel - multi-insert rows and retrieve ids

I'm using Laravel 4, and I need to insert some rows into a MySQL table, and I need to get their inserted IDs back.
For a single row, I can use ->insertGetId(), however it has no support for multiple rows. If I could at least retrieve the ID of the first row, as plain MySQL does, would be enough to figure out the other ones.
It's mysql behavior of
last-insert-id
Important
If you insert multiple rows using a single INSERT statement, LAST_INSERT_ID() returns the value generated for the first inserted row only. The reason for this is to make it possible to reproduce easily the same INSERT statement against some other server.
u can try use many insert and take it ids or after save, try use $data->id should be the last id inserted.
If you are using INNODB, which supports transaction, then you can easily solve this problem.
There are multiple ways that you can solve this problem.
Let's say that there's a table called Users which have 2 columns id, name and table references to User model.
Solution 1
Your data looks like
$data = [['name' => 'John'], ['name' => 'Sam'], ['name' => 'Robert']]; // this will insert 3 rows
Let's say that the last id on the table was 600. You can insert multiple rows into the table like this
DB::begintransaction();
User::insert($data); // remember: $data is array of associative array. Not just a single assoc array.
$startID = DB::select('select last_insert_id() as id'); // returns an array that has only one item in it
$startID = $startID[0]->id; // This will return 601
$lastID = $startID + count($data) - 1; // this will return 603
DB::commit();
Now, you know the rows are between the range of 601 and 603
Make sure to import the DB facade at the top using this
use Illuminate\Support\Facades\DB;
Solution 2
This solution requires that you've a varchar or some sort of text field
$randomstring = Str::random(8);
$data = [['name' => "John$randomstring"], ['name' => "Sam$randomstring"]];
You get the idea here. You add that random string to a varchar or text field.
Now insert the rows like this
DB::beginTransaction();
User::insert($data);
// this will return the last inserted ids
$lastInsertedIds = User::where('name', 'like', '%' . $randomstring)
->select('id')
->get()
->pluck('id')
->toArray();
// now you can update that row to the original value that you actually wanted
User::whereIn('id', $lastInsertedIds)
->update(['name' => DB::raw("replace(name, '$randomstring', '')")]);
DB::commit();
Now you know what are the rows that were inserted.
As user Xrymz suggested, DB::raw('LAST_INSERT_ID();') returns the first.
According to Schema api insertGetId() accepts array
public int insertGetId(array $values, string $sequence = null)
So you have to be able to do
DB::table('table')->insertGetId($arrayValues);
Thats speaking, if using MySQL, you could retrive the first id by this and calculate the rest. There is also a DB::getPdo()->lastInsertId(); function, that could help.
Or if it returened the last id with some of this methods, you can calculate it back to the first inserted too.
EDIT
According to comments, my suggestions may be wrong.
Regarding the question of 'what if row is inserted by another user inbetween', it depends on the store engine. If engine with table level locking (MyISAM, MEMORY, and MERGE) is used, then the question is irrevelant, since thete cannot be two simultaneous writes to the table.
If row-level locking engine is used (InnoDB), then, another possibility might be to just insert the data, and then retrieve all the rows by some known field with whereIn() method, or figure out the table level locking.
$result = Invoice::create($data);
if ($result) {
$id = $result->id;
it worked for me
Note: Laravel version 9

Selecting if the DB column is empty

I have a db that has a column that is empty and not using NULL.
How do I select the below column if its empty?
$this->db->where("{$this->_table['shop_shipping_rules']}.shop_shipping_rule_name");
Code:
$this->db->or_where("{$this->_table['shop_shipping_rules']}.shop_shipping_rule_country_iso", NULL);
$this->db->or_where("{$this->_table['shop_shipping_rules']}.shop_shipping_rule_country_iso", $country_iso);
$this->db->or_where("{$this->_table['shop_shipping_rules']}.shop_shipping_rule_region_code", $shop_shipping_rule_region_code);
$this->db->where("{$this->_table['shop_shipping_rules']}.shop_shipping_rule_name");
Try this
$this->db->where("{$this->_table['shop_shipping_rules']}.shop_shipping_rule_name",'');
works for me in Yii and Zend..

Getting last inserted index mysql

I am using ADODB to connect to my database.
After I submit the query I want to get the ID of the last inserted row (from the query just inserted).
ADODB has an Insert_ID() function that should retrieve this is but it is not...
db->Insert_ID()
is not working, neither is
db->Insert_ID($table, $key)
They both just return empty values.
I doubled checked my table and the insert statement is indeed working, a new row is being put in, and the key is auto_increment. Am I using the Insert_ID wrong or is there a better way to retrieve the key of the last row inserted?
Thanks
Edit: Adding code
$result = \PSU::db->Execute( $updateSQL, $values_array );
$id = \PSU::db->Insert_ID();
// $id = \PSU::db->Insert_ID( $table, $key );
\PSU::db is our ADODB implementation class, taking care of things like connecting, disconnecting, etc.
Is it possible that you are disconnecting and reconnecting to mysql between the query and the insert_id()?
Try this:
$result = \PSU::db->Execute( $updateSQL, $values_array );
return \PSU::db->_connectionID->insert_id ;
_connectionID must be fixed as is.
Hope it helps!

Categories