Is there any way where i can run Multiple semicolon separated query in Code Igniter without insert_batch() ?
e.g:
$a = 'INSERT INTO table (a,b,c) VALUES (1,2,3); INSERT INTO table1 (x,y,z) VALUES (1,2,3);';
$this->db->query($a);
Above code gives invalid query error.
If multiple tables with single data(Using Transactions) - (N table vs 1 Data)
Running Transactions Manually
$this->db->trans_begin();
$this->db->query('INSERT INTO table (a,b,c) VALUES (1,2,3)');
$this->db->query('INSERT INTO table1 (x,y,z) VALUES (1,2,3)');
if ($this->db->trans_status() === FALSE)
{
$this->db->trans_rollback();
}
else
{
$this->db->trans_commit();
}
Running Transactions Automatically
$this->db->trans_start();
$this->db->query('INSERT INTO table (a,b,c) VALUES (1,2,3)');
$this->db->query('INSERT INTO table1 (x,y,z) VALUES (1,2,3)');
$this->db->trans_complete();
If inserting Single table with multiple data (1 table vs N Data)
$data = array(
array(
'a' => 'My title 1' ,
'b' => 'My Name 1' ,
'c' => 'My date 1'
),
array(
'a' => 'My title 2' ,
'b' => 'My Name 2' ,
'c' => 'My date 2'
)
);
$this->db->insert_batch('mytable', $data);
Related
So I have 2 tables.
Table 1: (person_identity)
Id_person(PK), name, address, telp
Table 2: (Student)
Id_person(FK), no_student (PK), status, parent
How to input data to name, address, no_student, parent and status at the same time with the same Id_person but at 2 different table?
You can do like this
$dataPersonIdentity = ['name' => 'Abc', 'address' => 'This is address', 'telp' => 'this is telp'];
$this->db->insert('person_identity',$dataPersonIdentity);
$personIdentityId = $this->db->insert_id();
$dataStudent = ['Id_person' => $personIdentityId, 'no_student' => 8, 'status' => 1, 'parent' => 1];
do insert in the first table (person_identity)
and then do insert in the second table (student)
Im trying to insert the following array into my table to no avail. I tried several examples but none worked.
Each POST array contains two strings from an input form (each string from an input row) and the $data keys are of the same name of the columns in the table.
How do I insert this data into two rows with a single query?
$data = array(
'user_id' => $_POST['user_id'],
'order' => $_POST['order'],
'type' => $_POST['type'],
'series' => $_POST['series'],
'repetition' => $_POST['repetition'],
'load' => $_POST['load'],
'pause' => $_POST['pause']
);
EDIT.: Could swear I had copied the query.
$columns = implode(',',array_keys($data));
$values = implode(',',array_values($data));
$query = " INSERT INTO userdata ($columns) VALUES ($values)";
You can insert this type of array like this
$fields=" ".implode(",",array_keys($data))." ";
$data="'".implode ("','",$data)."'";
$query ="INSERT INTO table_name ($fields) VALUES ($data)";
if($query){
mysql_query($query);
}
I'm trying to insert some data into a database via codeigniter but am getting some strange errors. Does anyone know the cause:
My insert array ($datainsert) is the following when printed:
Array ( [online_name] => Discount Store
[online_nameKey] => d
[storeGroup_ID] =>
[CJ_ID] => 123456
[online_tag] => Health and Medical
[online_businessType] => 0
[online_businessTypeSub] => 0
[online_homepage] => http://www.discountstore.com
[store_ChainID] =>
[savingsdotcom_ID] => 0 )
Trying to print the insert I use:
echo $DB1->_insert('stores_online', $datainsert);
Which results in:
INSERT INTO stores_online (Discount Store, d, , 123456, Health and Medical, 0, 0, http://www.discountstore.com, , 0) VALUES ()
I can't figure out why its not using the array keys for the first () and the values correctly.
Try this code
$datainsert=Array ( [online_name] => Discount Store,
[online_nameKey] => d,
[storeGroup_ID] => something,
[CJ_ID] => 123456 ,
[online_tag] => Health and Medical ,
[online_businessType] => 0 ,
[online_businessTypeSub] => 0 ,
[online_homepage] => http://www.discountstore.com ,
[store_ChainID] => ,
[savingsdotcom_ID] => 0
) ;
$this->db->insert('stores_online', $datainsert);
Use
$this->db->insert('stores_online', $datainsert);
instead of
echo $DB1->_insert('stores_online', $datainsert);
I know the question is over a year, but I had the same issue and I solve it by creating the query manually this way:
public function add($data)
{
$query = 'INSERT INTO myTable (';
// (Column1, Column2, Column3,
foreach($data as $key => $column)
$query .= $key . ',';
// Removes the last comma
// Column3, == Column3) VALUES(
$query .= rtrim($query, ',') . ') VALUES(';
// Value1, Value2, Value3,
foreach($data as $key => $column)
$query .= "'" . $column . "',";
// Removes the last comma and closes the query
$query .= rtrim($query, ',') . ')';
// Result: INSERT INTO (Column1, Column2, Column3) VALUES ('VALUE1', 'VALUE2', 'VALUE3')
return $query;
}
This needs to be done:
echo $DB1->_insert('stores_online', array_keys($datainsert), $datainsert);
P.S. This works for CI 2.X and I have not tested it for other version of CI.
kindly enlightened me, which is faster/better approach or just the same between CI batch insert and loop insert.
$data = array(
array(
'title' => 'My title' ,
'name' => 'My Name' ,
'date' => 'My date'
),
array(
'title' => 'Another title' ,
'name' => 'Another Name' ,
'date' => 'Another date'
)
);
batch insert:
$this->db->insert_batch('mytable', $data);
/* produces: INSERT INTO mytable (title, name, date)
VALUES ('My title', 'My name', 'My date'),
('Another title', 'Another name', 'Another date'); */
loop insert (php):
for( $i = 0; $ < count($data); $i++ )
{
INSERT INTO mytable (title, name, date)
VALUES ($data[$i]['title'], $data[$i]['name'], $data[$i]['date'])
}
thanks!
Batch inserts are usually faster since they process the data in once, were as the INSERT has some overhead (eg, the SQL optimizer cannot deduct certain steps). That said, you need to process a tremendous number of rows to create a notable difference.
If your curious if it would matter anyway, then don't forget to also measure the time it costs the framework to map the classes to the database table(s). There's a good chance the ORM consumes more resources than a looped SQL INSERT.
Given this type of User table structure where you are storing many User values (such as phone #'s, preferences, contact info) in a table:
Table: User ID | Key | Value
$values = [
1 => 'A value for key 1',
2 => 'Hello',
8 => 'Meow',
]
// Update values
$stmt = $pdo_db->prepare('
INSERT INTO table (UID, KEY, VALUE)
VALUES (:UID, :KEY, :VALUE)
ON DUPLICATE KEY UPDATE VALUE = :VALUE');
foreach ($values as $key => $value) {
$stmt->bindParam(':KEY', $key);
$stmt->bindParam(':VALUE', $value);
$stmt->execute();
}
If you have 150 different pairs, thats 150 queries per update. How would I optimize this code? Would making a giant SQL make the work easier on the mysql side? Should I be looking at changing the structure itself?
Take this query as a guide-
INSERT INTO example
(example_id, name, value, other_value)
VALUES
(100, 'Name 1', 'Value 1', 'Other 1'),
(101, 'Name 2', 'Value 2', 'Other 2'),
(102, 'Name 3', 'Value 3', 'Other 3'),
(103, 'Name 4', 'Value 4', 'Other 4');
Allows you to insert multiple records at once.
If you know which records are new, it could speed up to separate those into a plain INSERT - mysql has to spend extra time reconciling the ON DUPLICATE... UPDATE otherwise.
Also think about using UPDATE or REPLACE if you're only updating.