Insert Data to Database Codeigniter only if item does not exit - mysql

I'm having trouble trying to insert batch data.
All is fine with the insert_batch function but i would like to insert only the items that does not exist in database, not update it, just ignore and insert new items.
This is my Controller:
csv file:
col0,col1,col2,col3
data1,data1,data1,data1
data2,data2,data,2,data2
data3,data3,data3,data3
insert batch:
function mres($q) {
if(is_array($q))
foreach($q as $k => $v)
$q[$k] = $this->mres($v); //recursive
elseif(is_string($q))
$q = mysql_real_escape_string($q);
return $q;
}
function inserbatch(){
$csv = 'file.csv';
$arrResult = array();
$handle = fopen("uploads/csv/".$csv, "r");
if( $handle ) {
while (($row = fgetcsv($handle, 0, ",")) !== FALSE) {
$arrResult[] = array(
'col0' => $row[0],
'col1' => $row[1],
'col2' => $row[2],
'col3' => utf8_encode($row[3])
);
}
fclose($handle);
}
$final = $this->mres($arrResult);
$this->model_m->addBatch($final);
}
Model:
public function addBatch($final = array()){
if($this->db->insert_batch('mytable', $final)){
return true;
}
return false;
}
database:
id,col0,col1,col2,col3
col0 contain the unique value and if exist in csv file need to be skipped.
My question is how can i insert only the data that doesnt exist in database the col0 is the unique value and i think need to be like
if data from csv[col0] != database[col0] insert_batch.
Any help is appreciated.

Yes I think you on the right path. You only need to check your db if the value exists.
Something like this:
foreach(csv[col0] as $your_data)
{
$query = $this->db->query("SELECT * FROM my_table WHERE col0 = $your_data");
$rows = $query->num_rows();
if(!$rows)
{
// No record has been found so here you would write the code to insert the data
}
}

Related

'Cannot create an empty shipment' while trying to create shipment in magento

I am trying to create shipment and adding tracking number after placing an order,but i am getting an error like Cannot create an empty shipment. when i search through google i got one of the reason for this is item quantity is null, but what i used below is returning the exact quantities of products ordered.
$itemQty = $order->getItemsCollection()->count();
I don't know exactly it is only the reason for that error. what i done mistake? anybody knows please help me on this.
public function salesOrderInvoiceShipmentCreate($observer)
{
// $order = $observer->getEvent()->getOrder();
//$order = Mage::getModel('sales/order')->loadByIncrementId($orderId);
$order_id = $observer->getData('order_ids');
$order = Mage::getModel('sales/order')->load($order_id);
$token = '3acb6561b04117c6cbe3552c90f1d6815507e257';
$waybill_url = 'https://track.delhivery.com/waybill/api/fetch/json/?token='.$token.'&cl=GEECHOO';
$waybill = file_get_contents($waybill_url);
Mage::log($order, Zend_Log::INFO, 'order.log', true);
if (!$order->getId()) {
Mage::throwException('Order does not exist, for the Shipment process to complete');
}
if ($order->canShip()) {
try {
// $shipment = Mage::getModel('sales/service_order', $order)
// ->prepareShipment($this->_getItemQtys($order));
$itemQty = $order->getItemsCollection()->count();
$shipment = Mage::getModel('sales/service_order', $order)->prepareShipment($itemQty);
$shipmentCarrierCode = '';
$shipmentCarrierTitle = '';
$arrTracking = array(
'carrier_code' => isset($shipmentCarrierCode) ? $shipmentCarrierCode : $order->getShippingCarrier()->getCarrierCode(),
'title' => isset($shipmentCarrierTitle) ? $shipmentCarrierTitle : $order->getShippingCarrier()->getConfigData('title'),
'tracking_number' => $waybill,
);
$track = Mage::getModel('sales/order_shipment_track')->addData($arrTracking);
$shipment->addTrack($track);
// Register Shipment
$shipment->register();
// Save the Shipment
$this->_saveShipment($shipment, $order);
// Finally, Save the Order
$this->_saveOrder($order);
} catch (Exception $e) {
throw $e;
}
}
}
Try this for order item quantity
$quote = Mage::helper('checkout/cart')->getCart()->getQuote();
$value = [];
foreach ($quote->getAllItems() as $item) {
$value[]= array (
'id' => $item->getSku(),
'quantity' => $item->getQty(),
}

how to get recently affected rows attribute in model of codeigniter

primary key of title table is id and it is an auto-increment when I insert data to the table I need to return the id of currently inserted row.
my model function is,
function addDate($x, $y, $z) {
$sql = "INSERT INTO title (title,no,user) VALUES ('$x','$y','$z')";
$query = $this->db->query($sql );
if($this->db->affected_rows() > 0) {
return "ok";
} else {
return "err";
}
}
Please help me on this.
You are wrong. In your function you are getting these three parameters ($x, $y, $z) But in code you are Inserting ('$t','$n','$a')(Question is edited)
Use $this->db->insert_id() to get last insert id
Try this
function addDate($x, $y, $z) {
$data = array(
'title' => $x ,
'no' => $y ,
'user' => $z
);
if(!$this->db->insert('title', $data)){
return FALSE ;
}
else{
$lastId = $this->db->insert_id(); # add this
return $lastId;
}
}
FYI: Don't use $x, $y, $z. use meaningful names like $title, $no, $user
Codeigniter Active Record Class Version 2.2.0

moving specific field value to another table before deleting the whole row

I have a table with 7 fields, when I delete a row from the table by id i want two fields of that row to be inserted into another table with just two columns.
This is my controller function
public function refund() {
$id = $this->uri->segment(4);
$accounts = $this->accounts_model->get_accounts_data_by_id($id);
foreach ($accounts as $row) {
$data = array(
'barcode' => $row->barcode,
'refunded_amount' => $row->refunded_amount,
);
}
$this->accounts_model->insert_refund($data);
$this->accounts_model->delete_accounts_data($id);
}
these are model functions
public function delete_accounts_data($id) {
$this->db->where('id', $id);
$this->db->delete('accounts');
}
public function insert_refund($data){
$this->db->insert('refund', $data);
}
Suppose this the row i will delete
id|name|barcode|refunded_amount|commission
01|asd |2342342| 53.01 | 5.32
on the other hand i will insert as
id|barcode|refunded_amount
01|2342342| 53.01
You should try and debug your code for general errors, e.g,
1) Try to set the environment to development in index.php.
2) Add some debugging code in your function to check for errors.
function refund(){
$id = $this->uri->segment(4);
$accounts = $this->accounts_model->get_accounts_data_by_id($id);
echo $this->db->last_query(); //will produce the query for fetching the details by id
if( isset( $accounts ) && count( $accounts ) > 0 ){
foreach ($accounts as $row) {
$data = array(
'barcode' => $row->barcode,
'refunded_amount' => $row->refunded_amount,
);
}
print_r( $data );
$this->accounts_model->insert_refund($data);
$this->accounts_model->delete_accounts_data($id);
}else{
echo "NO DATA FOUND";
}
}

insert if not exists Codeigniter

my controller:
function getFeed()
{
$feed_url = $this->input->get("url");
$content = file_get_contents($feed_url);
$x = new SimpleXmlElement($content);
foreach($x->channel->item as $entry) {
$feeds[] = array(
'title' => (string)$entry->title,
'url'=> (string)$entry->link,
'username' => $this->session->userdata('username')
);
$this->load->model('membership_model');
$this->membership_model->feeds($feeds);
}
Model:
function feeds($feeds_data)
{
$this->db->insert_batch('feeds', $feeds_data);
}
Is there a function to insert if only the row doesn't exists in the table? I have a table with 4 column : id,title,url,username. I have an anchor when i click him it calls geFeed function and insert the info into table. But i want to insert only if not exists.
I had the same challenge, so i eventually come up with a function which might be helpful to you.
function safe_update_batch($table_name,$records,$filter_field)
{
$filters=array();
foreach($records as $record)$filters[]=$record[$filter_field];
$this->db->query("SET SESSION group_concat_max_len=10000000");
$query=$this->db->select("GROUP_CONCAT($filter_field) AS existing_keys",FALSE)->where_in($filter_field, $filters)->get($table_name);
$row=$query->row();
$found_fields=explode(',',$row->existing_keys);
$insert_batch=array();
$update_batch=array();
foreach($records as $record)
{
if(in_array($record[$filter_field],$found_fields))$update_batch[]=$record;
else $insert_batch[]=$record;
}
if(!empty($insert_batch))$this->db->insert_batch($table_name,$insert_batch);
if(!empty($update_batch))$this->db->update_batch($table_name,$update_batch,$filter_field);
}
//sample usage
$this->safe_update_batch('feeds', $feeds_data,'title');
You can try this in your model!!
function insertClient($array)
{
$this->db->from('MyTable');
$this->db->where('Id', $array['Id']);
$query = $this->db->get();
if($query->num_rows() != 0){
$data = array(
'name'=>$array['name'],
'phone'=>$array['phone'],
'email'=>$array['email']
);
$this->db->where('Id', $array['Id']);
$this->db->update('CLIENTS', $data);
}else{
$data = array(
'name'=>$array['name'],
'phone'=>$array['phone'],
'email'=>$array['email']
);
$this->db->insert('CLIENTS',$data);
}
}
In controller:
$this->site_model->insertClient($_POST);
Sadly if you are using the active record class an INSERT IF NOT EXISTS function doesn't exist. You could try
Extending the active record class (easier said than done)
You could set indexes on certain columns as UNIQUE so that MySQL will check to see if it already exists
You could do some kind of SELECT before your INSERT to determine if the record is already there
For the queries where you need to do INSERT IF NOT EXISTS do $this->db->query('INSERT IF NOT EXISTS...')
function getFeed()
{
// Load the model up here - otherwise you are loading it multiple times
$this->load->model('membership_model');
$feed_url = $this->input->get("url");
$content = file_get_contents($feed_url);
$x = new SimpleXmlElement($content);
foreach($x->channel->item as $entry) {
// check if the feed is unique, if true then add to array
if( $this->membership_model->singleFeedIsUnique($entry) == TRUE ){
$feeds[] = array(
'title' => (string)$entry->title,
'url'=> (string)$entry->link,
'username' => $this->session->userdata('username')); }
} //foreach
// check to make sure we got any feeds with isset()
// if yes, then add them
if (isset($feeds)){ $this->membership_model->feeds($feeds); }
}
You can try this in your model and leave you controller without changes
function feeds($feeds_data)
{
$data = array(
title => $feeds_data[0],
url => $feeds_data[1],
username => $feeds_data[2]
);
$this->db->select('*');
$this->db->from('mytable');
$this->db->where('title',$feeds_data[0]);//you can use another field
if ($this->db->count_all_results() == 0) {
$query = $this->db->insert('mytable', $data);//insert data
} else {
$query = $this->db->update('mytable', $data, array('title'=>$feeds_data[0]));//update with the condition where title exist
}
}
you can check the id if you have it, adding in the data array and use it to check if exist

Output query to csv, codeigniter

I currently have a report that give me the users ID number and their email address, But I would like to make this in a CSV file instead of tables and rows like I currently have.
Here is my controller
function View_Email_E()
{
$data = array();
if($query = $this->report_model->View_Email_English())
{
$data['records'] = $query;
}
$data['main_content'] = 'view_all_email_english';
$this->load->view('includes/template', $data);
}
Here is my model
function View_Email_English()
{
$query = $this->db->where(array('Dial_Up' => '0', 'Language' => 'English', 'Membership_Status' => 'Active'));
$query = $this->db->like('Email', '#');
$query = $this->db->get('Membership');
return $query->result();
}
For some reason my view is not being shown in code mode, but it is an auto generated table using these this snippet of code. Each row returns ID and Email from the database.
<?php if(isset($records)) : foreach($records as $row) : ?>
How can I make a CSV file with just ID and email fields?
Thanks
I think you can use the csv_from_result function in dbutil to do it. Try something like this:
$csvContent = $this->dbutil->csv_from_result($query);
if ( ! write_file('./path/to/file.csv', $csvContent)) {
echo 'Unable to write the file';
} else {
echo 'File written!';
}
http://codeigniter.com/user_guide/database/utilities.html#csv
Add
$this->db->select(array('ID','Email'));
To your View_Email_English function.