empty field show error for insert batch in codeigniter - php

I have multiple form field. I want to insert more than 25 row in db with insert_batch in codeigniter. like
public function purchase(){
$data = array(
array(
'date'=> $this->input->post('date'),
'vendor_name'=>$this->input->post('vendor_name'),
'model'=>$this->input->post('model'),
'price' =>$this->input->post('price'),
'purchase_quantity'=>$this->input->post('quantity'),
'amount' =>$this->input->post('price')*$this->input->post('quantity'),
'invoice_no'=>$this->input->post('invoice')
),
array(
'date'=> $this->input->post('date'),
'vendor_name'=>$this->input->post('vendor_name2'),
'model'=>$this->input->post('model2'),
'price' =>$this->input->post('price2'),
'purchase_quantity'=>$this->input->post('quantity2'),
'amount' =>$this->input->post('price2')*$this->input->post('quantity2'),
'invoice_no'=>$this->input->post('invoice')
),
array(
'date'=> $this->input->post('date'),
'vendor_name'=>$this->input->post('vendor_name3'),
'model'=>$this->input->post('model3'),
'price' =>$this->input->post('price3'),
'purchase_quantity'=>$this->input->post('quantity3'),
'amount' =>$this->input->post('price3')*$this->input->post('quantity3'),
'invoice_no'=>$this->input->post('invoice')
)
);
$insert = $this->db->insert_batch('purchase',$data);
return $insert;
}
but if I complete two field and submit it show error like
Incorrect integer value: '' for column 'purchase_quantity' at row 3
INSERT INTO `purchase` (`amount`, `date`, `invoice_no`, `model`, `price`,
`purchase_quantity`, `vendor_name`) VALUES
(4995,'18-09-2014','vvvvv','m6','999','5','mizan'),
(5000,'18-09-2014','vvvvv','ab12','1000','5','abcde'), (0,'18-09-2014','vvvvv',0,0,'','')
Filename: C:\xampp\htdocs\final\sys\database\DB_driver.php
Line Number: 330
Please help.

use intval before integer values..
intval($this->input->post('quantity2'))
https://ellislab.com/forums/viewthread/238144/

It will be better if you use variables to insert batch data.
$purchase_quantity=empty($this->input->post('quantity3'))==true?0:$this->input->post('quantity3');
And use this $purchase_quantity in array to insert.
The code above will check if quantitiy3 have empty value (ie 0,null or false) it will replace with 0 (An integer) and save in variable that you can use in array to insert

you can set the values as null or default value if form elements are empty like this..
'date'=>($this->input->post('date'))?$this->input->post('date'):null;
or
'date'=>($this->input->post('date'))?$this->input->post('date'):date('Y-m-d');
Or do like this if you want to ignore insert totally:
$data = array();
for($i=1;$i<=25;$i++)
{
if($i>1)
{
if($this->input->post('vendor_name'.$i) && $this->input->post('model'.$i) && $this->input->post('price'.$i) && $this->input->post('quantity'.$i))
{
$record = array(
'date'=> $this->input->post('date'),
'vendor_name'=>$this->input->post('vendor_name'.$i),
'model'=>$this->input->post('model'.$i),
'price' =>$this->input->post('price'.$i),
'purchase_quantity'=>$this->input->post('quantity'.$i),
'amount' =>$this->input->post('price'.$i)*$this->input->post('quantity'.$i),
'invoice_no'=>$this->input->post('invoice')
);
$data[]=$record;
}
}
else{
if($this->input->post('vendor_name') && $this->input->post('model') && $this->input->post('price') && $this->input->post('quantity'))
{
$record = array(
'date'=> $this->input->post('date'),
'vendor_name'=>$this->input->post('vendor_name'),
'model'=>$this->input->post('model'),
'price' =>$this->input->post('price'),
'purchase_quantity'=>$this->input->post('quantity'),
'amount' =>$this->input->post('price')*$this->input->post('quantity'),
'invoice_no'=>$this->input->post('invoice')
);
$data[]=$record;
}
}
}

Related

Codeigniter, mysql, select_max and add 1 before inserting another record

When I insert a new record into a database table, I need to take an existing previous value of a column called el_order, add +1, and use that new el_order+1 to insert the new record with that value in the column.
I can't use autoincrement because I need to do some things with that column (reorder, move, etc) and have to use it as an integer.
Table
ID name el_order
1 1 1
21 bla 2
2 2 3
--NEW-- --NEW-- 3+1 (NEW)
I add a new record, and need to insert it with 3+1 in it's el_order column...
I have tried this, but no luck:
$this->db->select_max('el_order');
$res = $this->db->get('elem_diccio');
$eldi_key = url_title($this->input->post('id'), 'underscore', TRUE);
$el_order = $res+1;
$datos = array(
'ID' => $id,
'el_order' => $el_order,
'name' => $this->input->post('name'),
);
$this->db->insert('elem_diccio', $datos);
Just like this
$this->db->select_max('el_order');
$res = $this->db->get('elem_diccio')->row()->el_order;
$eldi_key = url_title($this->input->post('id'), 'underscore', TRUE);
$el_order = $res+1;
$datos = array(
'ID' => $id,
'el_order' => $el_order,
'name' => $this->input->post('name'),
);
$this->db->insert('elem_diccio', $datos);
$res is a CI_DB_mysqli_result Object. To get the column, you need
$this->db->select_max('el_order');
$res = $this->db->get('elem_diccio')->row();
$el_order = $res->el_order+1;
$datos = array(
'ID' => $id,
'el_order' => $el_order,
'name' => $this->input->post('name'),
);

Insert jQuery repeater row in PHP database

I have 1 row having 5 form fields. User can add/remove rows. Its repeatable row.
Now i want to store these fields into database with PDO php.
For normal values i am using this code but i am confused for repeater field.
$data = array(
'bill_no' => trim($_REQUEST['bill_no']),
'from_name' => trim($_REQUEST['from_name']),
'to_name' => trim($_REQUEST['to_name']),
'date' => trim($_REQUEST['date_bill']),
'mr_or_ms' => trim($_REQUEST['mr_or_ms']),
);
if($crud->InsertData("bill",$data)) {
header("Location: add-bill.php");
}
Insert Function:
public function InsertData($table,$fields) {
$field = array_keys($fields);
$single_field = implode(",", $field);
$val = implode("','", $fields);
try {
$query = $this->db->prepare("INSERT INTO ".$table."(".$single_field.") VALUES('".$val."')");
$query->execute();
return true;
} catch(PDOException $e) {
echo "unable to insert data";
}
}
Please help me to insert fields. Thanks
Change the names of your form fields, add [] to the end to get PHP arrays. For example change bill_no to bill_no[]. Something like this:
foreach($_REQUEST['bill_no'] as $row_number => $row_content){
$data = array(
'bill_no' => trim($_REQUEST['bill_no'][$row_number]),
'from_name' => trim($_REQUEST['from_name'][$row_number]),
'to_name' => trim($_REQUEST['to_name'][$row_number]),
'date' => trim($_REQUEST['date_bill'][$row_number]),
'mr_or_ms' => trim($_REQUEST['mr_or_ms'][$row_number]),
);
$crud->InsertData("bill",$data);
}
This assumes the browser is not mixing up the order of the fields, so maybe it's better to add unique names to the form fields when adding rows.
Also, there's no input data validation at all, please ensure you are escaping all data properly.
I did it with this method.
$total=count($_POST['description']);
for($i=0; $i<$total; $i++){
$data1 = array(
'bill_no' => trim($_POST['bill_no']),
'description' => trim($_POST['description'][$i]),
'nos' => trim($_POST['nos'][$i]),
'nos_day' => trim($_POST['nos_day'][$i]),
'pay' => trim($_POST['pay'][$i]),
'weekly_off' => trim($_POST['weekly'][$i]),
'hra' => trim($_POST['hra'][$i]),
'rs' => trim($_POST['rs'][$i]),
'ps' => trim($_POST['ps'][$i]),
);
$crud->InsertData("bill_details",$data1);
}

Drupal 7 Select query with If condition mysql database

function tablesort_example_page() {
//$date2=date('m-d-Y', strtotime('t.added_date'));
// if('t.status'==1){
// $status='Active';
// }else{
// $status='Inactive';
// }
// We are going to output the results in a table with a nice header.
$header = array(
// The header gives the table the information it needs in order to make
// the query calls for ordering. TableSort uses the field information
// to know what database column to sort by.
array('data' => t('S No'), 'field' => 't.id'),
array('data' => t('Country Name'), 'field' => 't.country_name'),
array('data' => t('Status'), 'field' => 't.status'),
array('data' => t('Added Date'), 'field' => 't.added_date'),
array('data' => t('Action'), 'field' => 't.id',),
array('data' => t('Action'), '',),
);
// Using the TableSort Extender is what tells the the query object that we
// are sorting.
$limit = 10;
$query = db_select('countries', 't')->extend('TableSort')->extend('PagerDefault')->limit($limit)->orderby('id', ASC);
$query->fields('t');
// Don't forget to tell the query object how to find the header information.
$result = $query
->orderByHeader($header)
->execute();
if('$row->status'==0){
$status='Active';
} else {
$status='Inactive';
}
$rows = array();
$i=1;
foreach ($result as $row) {
//print_r($row);
// Normally we would add some nice formatting to our rows
// but for our purpose we are simply going to add our row
// to the array.
$rows[] = array(
$row->id,
$row->country_name,
$status, ----> **
here i need to execute the If condition for $status
//$row->added_date,
date('d-m-Y H:i:s', strtotime($row->added_date)),
l('edit', 'mypages/countries/'. $row->id),
l('delete', 'mypages/delete/'. $row->country_name)
);
$i++;
}
As per my database table the below are my table fields.
(id, country_name, status, added_date)
In Status there will be 0 or 1
now my Question is i need to display status
if 0 - Inactive
1 - Active
I'd suggest using a PHP ternary operator to test the value in the status field and output a string description based on that value.
$rows[] = array(
$row->id,
$row->country_name,
($row->status == 0) ? 'Inactive' : 'Active',
date('d-m-Y H:i:s', strtotime($row->added_date)),
l('edit', 'mypages/countries/'. $row->id),
l('delete', 'mypages/delete/'. $row->country_name)
);

Error in getting the last inserted ID of a query using batch insert in CodeIgniter

How can I get the last inserted ID of a query using the batch insert in CodeIgniter. I used the code $this->db->insert_id() but it returns the ID of my first inserted array. I can't get the last insert.
Here's what I did:
for ($x = 0; $x < sizeof($filtername); $x++) {
$orders[] = array(
'poid' => null,
'order_id' => $poid,
'item_desc' => $filtername[$x],
'item_qty' => $filterquantity[$x],
'item_price' => $filterprice[$x],
'total' => $filtertotal[$x],
'cash_on_delivery' => $val_delivery,
'is_check' => $val_check,
'bank_transfer' => $val_transfer,
'transaction_date' => $dateorder
);
}
$this->db->insert_batch('po_order', $orders);
echo $this->db->insert_id(); //will return the first insert array
I can't spot where's my error. My last option is to get it using a query. I also did mysql_insert_id() but always returns to 0.
I think the best way would be to use the batch insert instead of individual inserts in a loop for performance , but to get the last insert id, ADD the First Insert ID & the Affected Rows.
$this->db->insert_batch('po_order', $orders);
$total_affected_rows = $this->db->affected_rows();
$first_insert_id = $this->db->insert_id();
$last_id = ($first_insert_id + $total_affected_rows - 1);
You will need to do something like this,
$insertIds = array();
for ($x = 0; $x < sizeof($filtername); $x++) {
$orders = array(
'poid' => null,
'order_id' => $poid,
'item_desc' => $filtername[$x],
'item_qty' => $filterquantity[$x],
'item_price' => $filterprice[$x],
'total' => $filtertotal[$x],
'cash_on_delivery' => $val_delivery,
'is_check' => $val_check,
'bank_transfer' => $val_transfer,
'transaction_date' => $dateorder
);
$this->db->insert('po_order', $orders);
$insertIds[$x] = $this->db->insert_id(); //will return the first insert array
}
print_r($insertIds); //print all insert ids

How to get all table columns without defining them in query?

I have two tables, User and Company. I have joining them like this:
$table = $this->getDbTable();
$select = $table->select();
$select->setIntegrityCheck( false );
$select->from( array('User'), array( 'id' => 'id',
'name' => 'User.name',
'gender' => 'User.gender',
'Company_id' => 'User.Company_id'
));
$select->join( 'Company', 'Company.id = User.Company_id',
array( 'Company_name' => 'Company.name' ,
'Company_address' => 'Company.address'
));
$rows = $table->fetchAll( $select );
It is working and giving me accurate result. Problem is that I have to mentions column names in above codes. I want to get all columns without mentioning them in above piece of code.
For example I want something like this that get all columns(But it is not providing all column values):
$table = $this->getDbTable();
$select = $table->select();
$select->setIntegrityCheck( false );
$select->from( array('User') );
$select->join( 'Company', 'Company.id = User.Company_id' );
$rows = $table->fetchAll( $select );
Thanks
Leaving away the second parameter to the from call should work: http://framework.zend.com/manual/en/zend.db.select.html#zend.db.select.building.columns

Categories