multi insert row & table codeigniter - php

i have 1 form new customer, which will insert into 2 table('tbcust' & 'tbcp'). I add button 'add new contact person' for insert row in table 'tcp', the button save in form will insert multiple table. table 'tbcust' is ok, but row 'nama_pt' in table 'tbcp' just passing 1 character.
CONTROLLER
public function post_multiple_table(){
$this->load->model('Multiple_model', 'multi_model', TRUE);
$cust_input_data = array();
//$cp_input_data = array();
$cust_input_data['nama_pt'] = $this->input->post('nama_pt');
$cust_input_data['tipe'] = $this->input->post('tipe');
$cust_input_data['alamat'] = $this->input->post('alamat');
$cust_input_data['email_cust'] = $this->input->post('email_cust');
$cust_input_data['notelp'] = $this->input->post('notelp');
$cust_input_data['nofax'] = $this->input->post('nofax');
$this->form_validation->set_rules('nama_orang[]', 'nama_orang', 'required|trim|xss_clean');
$this->form_validation->set_rules('nama_pt', 'nama_orang', 'required|trim|xss_clean');
$this->form_validation->set_rules('nohp[]', 'nohp', 'required|trim|xss_clean');
$this->form_validation->set_rules('email[]', 'email', 'required|trim|xss_clean');
if ($this->form_validation->run() == FALSE){
echo validation_errors(); // tampilkan apabila ada error
}else{
$nm = $this->input->post('nama_orang');
$result = array();
foreach($nm AS $key => $val){
$result[] = array(
"nama_orang" => $_POST['nama_orang'][$key],
"nama_pt" => $_POST['nama_pt'][$key],
"nohp" => $_POST['nohp'][$key],
"email" => $_POST['email'][$key]
);
}
model
public function create_multiple_tabel($nama_pt, $nama_orang){
$this->db->insert('tbcust', $nama_pt);
$this->db->insert_batch('tbcp', $nama_orang);
}
and this the form & database

Check in table tbcp if your row nama_pt have length set 1, and put 15 or higher if need.

Related

how multi update data on codeigniter

how to take the auto increment value to post.
here I insert two tables successfully, I create a condition after insertion, then update the data.
I have two tables, the first 'service' table and the second table 'customer_address'
customer_address table, has id_address as autoincrement.
when inserting data into two tables, I want to get the value id_address in the customer_address table. to be updated to the 'service' table.
public function import () {
include APPPATH.
'third_party/PHPExcel/PHPExcel.php';
$excelreader = new PHPExcel_Reader_Excel2007();
$loadexcel = $excelreader-> load('excel/'.$this-> filename.
'.xlsx'); //here I am loading data from an excel file for import
$sheet = $loadexcel->getActiveSheet()->toArray(null, true, true, true);
$data = array();
$numrow = 1;
foreach($sheet as $row) {
$a['acak'] = $this-> M_order-> bikin_kode();
$resi = $a['acak'];
$key1 = $this-> M_order-> db_cek($row['C']);
$origin = $key1['id_origin'];
if ($numrow > 1) {
array_push($data, array(
'tracking_number' => $resi,
'id_cs' => $row['B'],
'id_origin' => $origin,
'id_muat' => $row['D'],
));
$datax = array(
//'id_alamat' => this autoincrement
'id_cs' => $row['AM'],
'nama' => $row['AN'],
);
$this->db-> insert('customer_address', $datax);
// this update data to table service //
//here I am looping, to retrieve the address_id which was just at POST,
$isi = $this->db-> select('id_alamat')-> from('customer_address')->where('id_kota', $kot)->get()-> result();
foreach($sheet as $value) {
$hsl = array(
'id_muat' => $value - > id_alamat,
);
$this->db->update('service', $hsl);
}
}
$numrow++;
}
$this->M_order->insert_multiple($data); //to table service
}
when I updated the 'service' table I updated everything. how to update based on the data input only?
You must send id_alamat from view to your controller and make a unique code not just using autoincrement.
for example:
public function import () {
include APPPATH.
'third_party/PHPExcel/PHPExcel.php';
$excelreader = new PHPExcel_Reader_Excel2007();
$loadexcel = $excelreader-> load('excel/'.$this-> filename.
'.xlsx'); //here I am loading data from an excel file for import
$sheet = $loadexcel->getActiveSheet()->toArray(null, true, true, true);
$data = array();
$numrow = 1;
foreach($sheet as $row) {
$a['acak'] = $this-> M_order-> bikin_kode();
$resi = $a['acak'];
$key1 = $this-> M_order-> db_cek($row['C']);
$origin = $key1['id_origin'];
if ($numrow > 1) {
array_push($data, array(
'tracking_number' => $resi,
'id_cs' => $row['B'],
'id_origin' => $origin,
'id_muat' => $row['D'],
));
$datax = array(
'id_alamat' => $row['id_alamat'],
'id_cs' => $row['AM'],
'nama' => $row['AN'],
);
$this->db-> insert('customer_address', $datax);
// this update data to table service //
//here I am looping, to retrieve the address_id which was just at POST,
$isi = $this->db->select('id_alamat')->from('customer_address')->where('id_kota', $kot)->get()-> result();
//change $sheet to $isi
foreach($isi as $value) {
$hsl = array(
'id_muat' => $value->id_alamat,
);
$this->db->update('service', $hsl);
}
}
$numrow++;
}
$this->M_order->insert_multiple($data); //to table service
}

Codeigniter safest way of making update function with id on a hidden field

What's the safest way to do a function update having a hidden html input containing the id of the data?
<input type="text" name="request_id" value="<?php echo $param_request['idx']?>" style="display: none;">
Form validation is already included in my code and that's for making sure that all fields are required.
But how do I prevent someone from altering the hidden field (id)? What do I need to add in my update function in the controller for better security?
Here is my function in the controller:
public function update()
{
$this->load->library('form_validation');
$form_data = $this->input->post();
$idx = $this->input->post('request_id');
$form_request_type = $this->input->post('request_type');
$form_leave_start = $this->input->post('form-leave-start');
$form_leave_end = $this->input->post('form-leave-end');
$form_date_needed = $this->input->post('form-date-needed');
$form_amount_needed = $this->input->post('form-amount-needed');
$form_remarks = $this->input->post('redactor-textarea');
$form_refer = $this->input->post('refer');
$this->form_validation->set_data($form_data);
$this->form_validation->set_rules('refer[]', 'refer', 'required');
foreach ($form_data as $name=>$value) {
if($name!='refer'){
$this->form_validation->set_rules($name, $name, 'required');
}
}
//Checkboxes
$refer = json_encode($form_refer);
//Not common contents
$contents_info = json_encode(array(
'leave_start_date' => $form_leave_start,
'leave_end_date' => $form_leave_end,
'date_needed' => $form_date_needed,
'amount_needed' => $form_amount_needed,
'remarks' => $form_remarks
));
//Common contents
$common_info = array(
'requested_by_idx' => $this->session->userdata('member_index'),
'request_type' => $form_request_type,
'date_updated' => date("Y-m-d H:i:s A"),
'contents' => $contents_info,
'refer' => $refer,
'status' => 'PENDING'
);
$log = array(
'controller'=>'request',
'method'=>'update',
'item_idx'=>0,
'member_idx'=>$this->session->userdata('member_index'),
'member_category'=>$this->session->userdata('member_category')
);
$ret = $this->staffrequisition_model->updateItem($common_info, array('idx'=>$idx), $log);
echo json_encode(array('ret'=>($ret == true) ? 1 : 0));
}
And also I loaded the update view using an anchor tag with the id send in the link:
<i class="fa fa-edit"></i> Update
Receiving function:
public function update_request_view($idx)
{
$data = new stdClass;
$data->param_menu = 'request';
$type = $this->staffrequisition_model->getRequestType($idx);
$typeLower = strtolower($string = str_replace(' ', '', $type));
$commonContents = $this->staffrequisition_model->selectItem(array('idx'=> $idx));
$uncommonContents = json_decode($commonContents->contents);
$data->param_request = array_merge((array) $commonContents, (array) $uncommonContents);
$data->param_request_type = $type;
$data->param_refer = json_decode($data->param_request['refer']);
$this->load->view('dashboard/staff/update_'.$typeLower.'_view', $data);
}

Multiple Insert with dropdown codeigntier

I have3 table with name frm_data_aset,frm_monitor,frm_lokasi
I want if I insert on frm_data_aset column monitor_aset with dropdown from tabel monitor and lokasi from tabel lokasi. on table monitor column lokasi updated with data same at I insert from tabel data_Aset
this my structure :
enter image description here
enter image description here
now I get error :
Unknown column 'frm_monitor' in 'where clause'
UPDATE frm_monitor SET lokasi_monitor = '123' WHERE frm_monitor IS NULL
this my controller :
{
$this->_rules();
if ($this->form_validation->run() == FALSE) {
$this->create();
} else {
$data = array(
'lokasi_aset' => $this->input->post('lokasi_aset',TRUE),
'monitor_aset' => $this->input->post('monitor_aset',TRUE),
);
$id= $this->input->post('kd_monitor', TRUE);
$data = array(
'lokasi_monitor' => $this->input->post('lokasi_aset'),
);
$this->M_monitor->update_lokasi($id,$data);
$this->M_data_aset->insert($data);
redirect(site_url('data_aset'));
}
}
this my model M_monitor
function update_lokasi($id,$data){
$this->db->where('frm_monitor', $id);
$this->db->update('frm_monitor', $data);
}
and this my dropdown monitor at form insert data_aset
<option value="0">Pilih Monitor</option>
<?php
$monitor = $this->db->get('frm_monitor')->result();
foreach ($monitor as $row){
echo "<option value='$row->kd_monitor' ";
echo $row->kd_monitor==$monitor_aset?'selected':'';
echo ">". strtoupper($row->kd_monitor)."</option>";
}
?>
try changing your model query as like this
function update_lokasi($id,$data){
$this->db->where('id_monitor', $id);
$this->db->update('frm_monitor', $data);
}
Before that make sure that the post for 'kd_monitor' in the controller is not null
You should rename the $data variable being passed to $this->M_monitor->update_lokasi() because it will overwrite $data that is going to be passed to $this->M_data_aset->insert() with only 'lokasi_monitor' array on it. Or even better try rename both $data to prevent confusion.
Modify your controller :
{
$this->_rules();
if ($this->form_validation->run() == FALSE) {
$this->create();
} else {
$data_aset = array(
'lokasi_aset' => $this->input->post('lokasi_aset',TRUE),
'monitor_aset' => $this->input->post('monitor_aset',TRUE),
);
$id = $this->input->post('kd_monitor', TRUE);
$data_monitor = array(
'lokasi_monitor' => $this->input->post('lokasi_aset'),
);
$this->M_monitor->update_lokasi($id,$data_monitor);
$this->M_data_aset->insert($data_aset);
redirect(site_url('data_aset'));
}
}
And change 'frm_monitor' to 'kd_monitor' on the conditional query :
function update_lokasi($id,$data){
$this->db->where('kd_monitor', $id);
$this->db->update('frm_monitor', $data);
}

CButtonColumn approve button executes PHP code without being clicked

I have this code that would create and populate a table in Yii CGridView.
My problem is the function located in the 'approve'=>array('options'=>array('onclick')) is being called for every refresh of the page even if the approve button isn't clicked.
I determined the mistake occurs by printing the value of the counter. The counter should only increment by 1 when approved is clicked not for every refresh of the page.
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'registrants-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
'user_id',
'first_name',
'middle_name',
'last_name',
'gender',
'shirt_size',
'receipt_number',
'category',
array(
'class'=>'CButtonColumn',
'template'=>'{approve}, {update},{delete}',
'buttons'=>array(
'approve' => array(
'label'=>'Approve',
'options'=>array(
'onclick'=> $model->approveRegistrants($model->user_id, $model->category),
//ending approve-option array
),
//ending approve-button array
),
//ending buttons array
)
//ending table-last-column array
),
//ending table-columns array
),
//ending zii.widgets.grid.CGridview
));
?>
This is my function in my model.
public function approveRegistrants($user_id, $category){
$db = new PDO('mysql:host=localhost; dbname=secret; charset=utf8', 'Andy', '*****');
$getCounter = "SELECT registrants FROM counter order by registrants desc limit 1;";
$bool = false;
$show = '0';
do{
$result = $db->query($getCounter);
// $registrants = $db->query($getCounter);
// $result->setFetchMode(PDO::FETCH_ASSOC);
// $registrants = '1';
foreach ($result as $value){
$registrants = $value['registrants'];
echo 'hello'.$registrants.'</br>';
}
// $registrants = $result['registrants'];
// print_r($registrants);
$max_registrants = '3400';
if($max_registrants > $registrants){
// pdo that will use $updateCounterByOne
$updateCounterByOne = "UPDATE counter set registrants = registrants + 1 WHERE registrants = ". $registrants .";";
$updateCounter = $db->prepare($updateCounterByOne);
$updateCounter->execute();
// return affected rows
$returnAffectedRows = $updateCounter->rowCount();
$bool = true;
// break;
}
else{
echo "No more slot Available";
// break;
}
}while($returnAffectedRows == '0');
if($bool = true){
//sql syntax
$selectApprovedUser = "SELECT user_id FROM registrants WHERE user_id = '". $user_id ."';";
//pdo that will use $selectApprovedUser
$updateApprovedUser = "UPDATE registrants set approved = 'YES' where user_id = ". $selectApprovedUser .";";
$updateApproved = $db->prepare($updateApprovedUser);
$updateApproved->execute();
//pdo that will use $insertApprovedUser
$insertApprovedUser = "INSERT INTO approved_registrants (user_id, category, approved_date) VALUES ('".$user_id."', '".$category."', 'curdate()');";
$insertApproved = $db->prepare($insertApprovedUser);
$insertApproved->execute();
//execute trial
$selectSomething = "SELECT registrants from counter where tandem = '0'";
$doSelect = $db->prepare($selectSomething);
$doSelect->execute();
$hello = $doSelect->fetchAll();
echo $hello[0]['registrants'];
}
}
What I'm trying to achieve is when approve button is clicked it will get the user_id and will do the PDO commands such as the update and insert.
If you see CButtonColumn, it states that 'options' takes in key-value pairs for the HTML tag attributes. Therefore, you should not place PHP code here like what you did here, unless you want them executed immediately. This is wrong:
'options'=>array(
'onclick'=> $model->approveRegistrants($model->user_id, $model->category),
),
What you want is a TbToggleColumn column from YiiBooster extension to approve/unapprove items:
array(
'class' => 'bootstrap.widgets.TbToggleColumn',
'toggleAction' => 'user/toggleApproved',
'name' => 'isApproved',
'header' => 'Approved?'
),
You will also need a corresponding action in the controller. Don't forget to add 'toggleApproved' to the controller filters. In this example, I have simply inverted the value of a single column, but you may do other stuff with this action.
public function actionToggleApproved($id) {
$model = $this->loadModel($id);
if(!is_null($model) && $model->hasAttribute('isApproved')) {
$model->isApproved = $model->isApproved == 0 ? 1 : 0;
$model->update(); // no validation
}
}

Hook to Add a Value in a SugarCRM Custom Field

I am new to SugarCRM. I've created a custom field named 'account name' in the Meetings module so that if we select Contacts from related to field, the 'account name' of that Contact is automatically added to the field.
Here's my code:
$hook_array['after_retrieve'] = Array();
$hook_array['after_retrieve'][] = Array(1, 'Add custom account',
'custom/modules/Meetings/AddAccount.php','AddAccount', 'addAcc');
LogicHook:
class AddAccount
{
public function addAcc(&$bean, $event, $arguments)
{
global $current_user;
global $db;
echo "<pre>";
$meeting_id = $_REQUEST['record'];
$query = "SELECT * FROM `meetings_contacts` WHERE `meeting_id` LIKE '$meeting_id'";
$result = $bean->db->query($query, true, " Error filling in additional detail fields: ");
if ($bean->db->getRowCount($result) > 0) {
while ($row = $bean->db->fetchByAssoc($result)) {
$contact_id = $row['contact_id'];
}
if (isset($contact_id)) {
$query1 = "SELECT * FROM `accounts_contacts` WHERE `contact_id` LIKE '$contact_id'";
$result1 = $bean->db->query($query1, true, " Error filling in additional detail fields: ");
while ($row1 = $bean->db->fetchByAssoc($result1)) {
$account_id = $row1['account_id'];
}
$query2 = "SELECT * FROM `accounts` WHERE `id` LIKE '$account_id'";
$result2 = $bean->db->query($query2, true, " Error filling in additional detail fields: ");
while ($row2 = $bean->db->fetchByAssoc($result2)) {
$account_name = $row2['name'];
}
$update_custom_account = "UPDATE `meetings_cstm` SET `accountname_c` = '$account_name' WHERE `meetings_cstm`.`id_c` = '$meeting_id';";
$Change = $bean->db->query($update_custom_account);
}
}
}
}
The problem is that the field is getting added but the "i" in the ListView has stopped working. Is there a simpler way than this long query?
Thanks in advance.
This is a better way of doing the above.
custom/modules/Meetings/logic_hooks.php
// position, file, function
$hook_array['after_retrieve'] = Array();
$hook_array['after_retrieve'][] = Array(1, 'Add custom account', 'custom/modules/Meetings/AddAccount.php', 'AddAccount', 'getAccountName');
$hook_array['after_save'] = Array();
$hook_array['after_save'][] = Array(1, 'Add custom account', 'custom/modules/Meetings/AddAccount.php', 'AddAccount', 'getAccountName');
custom/modules/Meetings/AddAccount.php
class AddAccount {
public function getAccountName(&$bean, $event, $arguments) {
if ($bean->parent_type == 'Contacts') {
$contact = BeanFactory::getBean('Contacts', $bean->parent_id);
$contact->load_relationship('accounts_contacts');
$account = BeanFactory::getBean('Accounts', $contact->account_id);
$bean->account_name_c = $account->name;
}
}
}
This way, you are using the bean and not SQL.
EDIT:
To add the new field, you can create this fileā€¦
custom/Extension/modules/Meetings/Ext/Vardefs/account_name_c.php
<?php
$dictionary['Meeting']['fields']['account_name_c'] =
array (
'name' => 'account_name_c',
'vname' => 'LBL_ACCOUNT_NAME_C',
'type' => 'varchar',
'len' => '255',
'unified_search' => true,
'comment' => 'Account name for meeting',
'studio' => 'true',
);
Then after a Repair/Rebuild, go to Studio > Meetings > Layouts > ListView and drag/drop the new field from 'Hidden' to 'Default.' Select the 'Save & Deploy' button, and after saving the Meeting record, your account name will appear in the list view.

Categories