Prepare SQL statements and enter only if not duplicates - php

I am creating a Sales Order form for the small business I work for. I have a form that connects to a database for drop-down menus and then text boxes to add new data if needed. There are four more sections that can appear if all data boxes are filled in in the section prior.
The inputs that link to the database include Company, Customer, Tool and Part And then there is a Description to enter on work to be done. So once Tool, Part, and Description have been filled in, a second section with another Tool, Part, and Description come into view. I have a script I have called Update.php that determines what fields have been filled and thus what to enter into the database. What I have been trying to do is to avoid duplicate entries. So if on the first section a UpdateNewTool has been inputted and then on the second section that is put into that field again to associate another Part with it, that data will be inserted twice. How can I go about throwing out one of those input statements?
My update.php code:
<?php
$servername = "localhost";
$username = "user";
$password = "password";
$dbname = "Sales_Orders";
$UpdateCompany=$_POST['UpdateCompany'];
$UpdateNewCompany=$_POST['UpdateNewCompany'];
$UpdateCustomer=$_POST['UpdateCustomer'];
$UpdateNewCustomer=$_POST['UpdateNewCustomer'];
$UpdateTool=$_POST['UpdateTool'];
$UpdateTool2=$_POST['UpdateTool2'];
$UpdateTool3=$_POST['UpdateTool3'];
$UpdateTool4=$_POST['UpdateTool4'];
$UpdateNewTool=$_POST['UpdateNewTool'];
$UpdateNewTool2=$_POST['UpdateNewTool2'];
$UpdateNewTool3=$_POST['UpdateNewTool3'];
$UpdateNewTool4=$_POST['UpdateNewTool4'];
$UpdateNewPart=$_POST['UpdateNewPart'];
$UpdateNewPart2=$_POST['UpdateNewPart2'];
$UpdateNewPart3=$_POST['UpdateNewPart3'];
$UpdateNewPart4=$_POST['UpdateNewPart4'];
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$data = [];
// BEGIN CONDITIONAL STATEMENTS
// New Company added by itself
if (!empty($UpdateNewCompany)) {
$data[] = [ '1', $UpdateNewCompany, $UpdateNewCompany, NULL ];
$data[] = [ '2', '', '', $UpdateNewCompany ];
$data[] = [ '3', '', '', $UpdateNewCompany ];
}
//Using the Company Drop-down box
if (!empty($UpdateCompany)) {
$UpdateNewCompany = $UpdateCompany; // If there is no new company inserted, $UpdateNewCompany becomes $UpdateCompany
if (!empty($UpdateNewCustomer)) {
$data[] = [ '2', $UpdateNewCustomer, $UpdateNewCustomer, $UpdateNewCompany ];
}
if (empty($UpdateTool)) { //If there is a new tool to add
if (!empty($UpdateNewTool)) {
$data[] = [ '3', $UpdateNewTool, $UpdateNewTool, $UpdateNewCompany ];
$data[] = [ '4', '', '', $UpdateNewTool ];
}
if (!empty($UpdateNewPart)) {
$data[] = [ '4', $UpdateNewPart, $UpdateNewPart, $UpdateNewTool ];
}
}
if (!empty($UpdateTool)) { // If there is no new tool to add
$UpdateNewTool = $UpdateTool;
if (!empty($UpdateNewPart)) {
$data[] = [ '4', $UpdateNewPart, $UpdateNewPart, $UpdateNewTool ];
}
}
//Part 2
if (empty($UpdateTool2)) { //If there is a new tool to add
if (!empty($UpdateNewTool2)) {
$data[] = [ '3', $UpdateNewTool2, $UpdateNewTool2, $UpdateNewCompany ];
$data[] = [ '4', '', '', $UpdateNewTool2 ];
}
if (!empty($UpdateNewPart2)) {
$data[] = [ '4', $UpdateNewPart2, $UpdateNewPart2, $UpdateNewTool2 ];
}
}
if (!empty($UpdateTool2)) { // If there is no new tool to add
$UpdateNewTool2 = $UpdateTool2;
if (!empty($UpdateNewPart2)) {
$data[] = [ '4', $UpdateNewPart2, $UpdateNewPart2, $UpdateNewTool2 ];
}
}
//Part 3
if (empty($UpdateTool3)) { //If there is a new tool to add
if (!empty($UpdateNewTool3)) {
$data[] = [ '3', $UpdateNewTool3, $UpdateNewTool3, $UpdateNewCompany ];
$data[] = [ '4', '', '', $UpdateNewTool3 ];
}
if (!empty($UpdateNewPart3)) {
$data[] = [ '4', $UpdateNewPart3, $UpdateNewPart3, $UpdateNewTool3 ];
}
}
if (!empty($UpdateTool3)) { // If there is no new tool to add
$UpdateNewTool3 = $UpdateTool3;
if (!empty($UpdateNewPart3)) {
$data[] = [ '4', $UpdateNewPart3, $UpdateNewPart3, $UpdateNewTool3 ];
}
}
//Part 4
if (empty($UpdateTool4)) { //If there is a new tool to add
if (!empty($UpdateNewTool4)) {
$data[] = [ '3', $UpdateNewTool4, $UpdateNewTool4, $UpdateNewCompany ];
$data[] = [ '4', '', '', $UpdateNewTool4 ];
}
if (!empty($UpdateNewPart4)) {
$data[] = [ '4', $UpdateNewPart4, $UpdateNewPart4, $UpdateNewTool4 ];
}
}
if (!empty($UpdateTool4)) { // If there is no new tool to add
$UpdateNewTool4 = $UpdateTool4;
if (!empty($UpdateNewPart4)) {
$data[] = [ '4', $UpdateNewPart4, $UpdateNewPart4, $UpdateNewTool4 ];
}
}
}
$insert = $conn->prepare("INSERT INTO Sales_Orders_dynlist_items (listid,name,value,parent) VALUES (?, ?, ?,?)");
if ( $insert === false ) {
echo "Error:".$conn->error;
die;
}
foreach ( $data as $item ){
if ( $insert->bind_param("ssss", ...$item) === false ) {
echo "Error:".$conn->error;
}
if ( $insert->execute() === false ) {
echo "Error:".$conn->error;
}
}
$conn->close();
?>
I'm pretty sure the place that needs work will be:
foreach ( $data as $item ){
if ( $insert->bind_param("ssss", ...$item) === false ) {
echo "Error:".$conn->error;
}
if ( $insert->execute() === false ) {
echo "Error:".$conn->error;
}
}
So for instance, sometimes we will need different parts with the same tool number. Therefore, if the user puts in a new job number such as "1234" and Part "abcd" then a description as to what's done. Then in the next section, "1234" isn't in the dropbox yet as it hasn't been added to the database yet. So the user puts "1234" in the tool again but "dcba" as the part and another description. Once submitted there will be two entries in the database with ['3', '1234', '1234', 'Whatever Company'];
Thanks for any input!

So I decided to take a different approach at this. What I ended up doing was set up a javascript script that determined if the NewTool input box was empty and if not, add that input value as an option to the Tool2 and so on boxes. The javascript is as follows:
function addOpTool() {
if(document.getElementById('NewTool').value != '') {
var x = document.getElementById("Tool2");
var y = document.getElementById("Tool3");
var z = document.getElementById("Tool4");
var test = document.getElementById("NewTool");
var option = document.createElement("option");
var option2 = document.createElement("option");
var option3 = document.createElement("option");
option.text = test.value;
option2.text = test.value;
option3.text = test.value;
x.add(option);
y.add(option2);
z.add(option3);
}
}
function addOpTool2() {
if(document.getElementById('NewTool2').value != '') {
var y = document.getElementById("Tool3");
var z = document.getElementById("Tool4");
var test = document.getElementById("NewTool2");
var option2 = document.createElement("option");
var option3 = document.createElement("option");
option2.text = test.value;
option3.text = test.value;
y.add(option2);
z.add(option3);
}
}
function addOpTool3() {
if(document.getElementById('NewTool3').value != '') {
var z = document.getElementById("Tool4");
var test = document.getElementById("NewTool3");
var option3 = document.createElement("option");
option3.text = test.value;
z.add(option3);
}
}
I added these functions to the appropriate onchange of NewTool, NewTool2, and NewTool3.
So for instance the user inputs "1234" in NewTool and "LH-Side" in NewPart. Then in the following form section there is now an option of "1234" in the Tool2 dropdown box and the user can just select that and then input "RH-Side" in NewPart2.
When submitting the form, only ONE instance of the tool# "1234" will be put into the database, solving the problem I was running into!

Related

Insert Batch php mysql with check duplicate and sum values of field duplicate

i have 1 million data using foreach.
ex table:
table
the data
data
i want to inserting that's data using batch/multipleinsert, but i have problem when i got duplicate data. if data duplicate i want the field amount will sum and update amount field with sum amount duplicated data.
this is my code before
<?php
foreach ($data_transaksi as $key)
{
if($key['STATUS_COA'] != $key['CHART_OF_ACCOUNT_STATUS'])
{
if($key['ACCOUNT_CATEGORY_CODE'] == '9')
{
$amount = round($key['AMOUNT'],2);
}
else
{
$amount = round($key['AMOUNT'],2) *-1;
}
}
else
{
if($key['ACCOUNT_CATEGORY_CODE'] == '9')
{
$amount = round($key['AMOUNT'],2)*-1;
}
else
{
$amount = round($key['AMOUNT'],2);
}
}
$dt_exsis = $this->ledger_model->cek_data_coa_exsis($key['COA_CODE'],$modul,$ID_USER);
if(empty($dt_exsis['id']))
{
//TRYINSERTINGBATCH
// $datainsert[] = '('.$key['COA_CODE'].','.$amount.','.$ID_USER.',"'.$modul.'")';
// $test = $key['COA_CODE'];
$datainput = array(
'COA_CODE' => $key['COA_CODE'],
'AMOUNT' => $amount,
'MODUL' => $modul,
'USER_ID' => $ID_USER
);
$this->ledger_model->save_rows_to_table($datainput,'finance_lapkue_temp');
}
else
{
$amount_fix = $amount + $dt_exsis['AMOUNT'];
$data=array(
'AMOUNT' => $amount_fix
);
$this->ledger_model->edit_rows_to_table_where($data,'finance_lapkue_temp','id',$dt_exsis['id']);
// $q = "UPDATE finance_lapkue_temp set AMOUNT = '$amount_fix' where id = '".$dt_exsis['id']."'";
// $this->db->query($q);
}
// $data_amount[$key['COA_CODE']] += $amount;
}
?>
if i using this code, the proccess so slow
Good option will to pass only data to DB that you want to insert. All the data cleaning task can be done in controller.
// Create a data array and add all info
$data = [];
//if user does not exist add it in array
if (empty($dt_exist($id))) {
$data[$ID_USER] = array(
'COA_CODE' => $key['COA_CODE'],
'AMOUNT' => $amount,
'MODUL' => $modul,
'USER_ID' => $ID_USER
);
}
else {
//if user exist in $data just modify the amount
if (!empty($data[$ID_USER])) {
$data[$ID_USER]['AMOUNT'] += $dt_exsis['AMOUNT'];
}
else {
// if user does not exist in data create add all info
$data[$dt_exsis['ID_USER']] = array(
'COA_CODE' => $dt_exsis['COA_CODE'],
'AMOUNT' => $dt_exsis['amount'],
'MODUL' => $dt_exsis['modul'],
'USER_ID' => $dt_exsis['ID_USER']
);
}
}
This will save multiple calls to DB and at the end you can pass $data and do multiple insert.

Yii2 Sum of a Column Based on Filter Option

I have a GridView and 6 filter options placed on radio buttons. When I click a filter, the GridView will change based on the filter being clicked. Here's a picture:
Now, I want to get the total Converted Amount of the table based on the filter chosen. For example, if I choose Draft filter, the table will show all Draft reimbursements and will sum up its Converted Amount and total will be placed at the top right side above the table as shown in the photo.
I tried googling solutions for this one but I find no answer. Here's a snippet of my code in my controller:
$refreshData = false;
if (isset(Yii::$app->request->getBodyParams()['sortby'])) {
$refreshData = true;
$sortby = Yii::$app->request->getBodyParams()['sortby'];
} else {
$sortby = 'Show All';
$dataProvider = new ActiveDataProvider([
'query' => Reimbursement::find()->where(['company_id' => new \MongoId($session['company_id'])])
]);
}
// get all reimbursements
$reimbursements = Reimbursement::findAll(['company_id' => new \MongoId($session['company_id'])]);
if (isset(Yii::$app->request->getBodyParams()['sortby'])) {
if(Yii::$app->request->getBodyParams()['sortby'] != '' && Yii::$app->request->getBodyParams()['sortby'] != 'Show All') {
$refreshData = true;
$reimbursements = Reimbursement::findAll(['company_id' => new \MongoId($session['company_id']), 'status' => Yii::$app->request->getBodyParams()['sortby']]);
// $ids = [];
// foreach ($reimbursements as $i => $model) {
// $ids[] = $model['_id'];
// }
// $command = Yii::$app->db->createCommand('SELECT sum(total) FROM estimate WHERE `_id` IN ('.implode(',',$ids).')'); // please use a prepared statement instead, just a proof of concept
// $sum = $command->queryScalar();
} elseif (Yii::$app->request->getBodyParams()['sortby'] == 'Show All') {
$refreshData = true;
}
}
$dataProvider = new ArrayDataProvider([
'allModels' => $reimbursements,
]);
if($refreshData) {
return $this->renderPartial('_index', [
'dataProvider' => $dataProvider,
]);
}
$dataProvider->pagination->pageSize = 10;
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
'rModel' => $rModel,
]);
As you may have noticed I commented some lines of code below if(Yii::$app->request->getBodyParams()['sortby'] != '' && Yii::$app->request->getBodyParams()['sortby'] != 'Show All') condition. I tried that one and it doesn't work.
How do I implement this?
$reimbursements = Reimbursement::find()->where(['company_id' => new \MongoId($session['company_id'])]);
if (isset(Yii::$app->request->getBodyParams()['sortby'])) {
$refreshData = true;
$sortby = Yii::$app->request->getBodyParams()['sortby'];
$reimbursements->andWhere(['status' => Yii::$app->request->getBodyParams()['sortby']]);
} else {
$refreshData = false;
$sortby = 'Show All';
}
$dataProvider = new ActiveDataProvider([
'query' => $reimbursements,
]);
$totalSum = $reimbursements->sum('total');

Using render() value does not update when color box open second time

I'm posting value using color box from view to controller. First time it works perfectly fine but when I reopen the color box it POST the old value to the new.
This is my color box code:
$('#equipmentPopup').colorbox({
ajax: true,
width: "620px",
height: "450px",
href: showEquipment,
data: {
briefingId: $("#briefing_id").val(),
briefingDate: $("#Briefing_scheduled_date").val(),
briefingEndDate: $("#Briefing_scheduled_end_date").val(),
briefingEquipments: $('#BriefingEquipments').val()
}
});
This is my action code:
public function actionShowEquipment()
{
$this->layout = "//layouts/popup";
$equipmentConflicts = '';
$briefingId = $_POST['briefingId'];
$briefingDate = $_POST['briefingDate'];
$briefingEndDate = isset($_POST['briefingEndDate']) ? $_POST['briefingEndDate'] : '';
$serializeBriefingEquipments = isset($_POST['briefingEquipments']) ? $_POST['briefingEquipments'] : '';
$equipment = CHtml::listData(Equipment::model()->findAll(), 'id', 'name');
$briefingCenter = BriefingCenter::model()->findByPk(Yii::app()->user->currentBriefingCenterId);
if ($briefingId) {
$briefingEquipmentArr = BriefingEquipment::model()->findAll('briefing_id = :bId', array(':bId' => $briefingId));
if (!$briefingEquipmentArr) {
$briefingEquipmentArr[] = new BriefingEquipment();
}
} else if ($serializeBriefingEquipments) {
$serializeBriefingEquipments = unserialize($serializeBriefingEquipments);
}
$briefing = Briefing::model()->findByPk($briefingId);
if (!empty($briefing->scheduled_date) && !empty($briefing->scheduled_end_date)) {
$minDate = $briefing->scheduled_date;
$maxDate = $briefing->scheduled_end_date;
} else {
$minDate = $briefingDate;
$maxDate = $briefingEndDate;
}
echo $this->render('edit/equipment', array(
'briefing' => array(
'briefingId' => $briefingId,
'briefingDate' => $briefingDate,
'briefingEndDate' => $briefingEndDate,
),
'minDate' => strtotime($minDate),
'maxDate' => strtotime($maxDate),
'briefingEquipmentArr' => $briefingEquipmentArr,
'equipments' => $equipment,
'briefingCenter' => $briefingCenter,
'serializeBriefingEquipments' => $serializeBriefingEquipments,
'dateFormat' => Yii::app()->user->currentBriefingCenterDateFormat,
));
}
Your code does not work for me. I see there is no passed data by colorbox, so try changing data to this:
data: function() {
return {
briefingId: $("#briefing_id").val(),
briefingDate: $("#Briefing_scheduled_date").val(),
briefingEndDate: $("#Briefing_scheduled_end_date").val(),
briefingEquipments: $('#BriefingEquipments').val()
}
}
Maybe it will help.

PHP not deleting and inserting data right

How this code works is every time a user visits the page, i scrape all of the data from the table and pass it through the below posts. If the user hasn't accessed that page before and the database is empty with their cookie_id, then it inserts the content, if it is found then it deletes the content from the database and inserts it again. The problem I am having though is that when the deletion occurs it deletes everything and seems to insert one value from $data1 instead of all the data from $data. Any ideas as to why this is happening?
Backend:
$cookie_id = $this->input->cookie("session_id");
$selected_size = $this->input->post('selected_size');
$product_id = $this->input->post('product_id');
$product_name = $this->input->post('product_name');
$product_color = $this->input->post('product_color');
$q1 = $this->db->query("SELECT * FROM default_cart_temp
WHERE cookie_id = '$cookie_id'
AND is_paid = 'No'");
if ($q1->num_rows() > 0) {
$this->db->where('cookie_id', $cookie_id);
$this->db->delete('default_cart_temp');
foreach($product_id as $key => $value) {
$data1 = array('selected_size' => $selected_size[$key],
'product_id' => $value,
'product_name' => $product_name[$key],
'product_color' => $product_color[$key],
'cookie_id' => $cookie_id,
'is_paid' => 'No');
} $this->db->insert('default_cart_temp', $data1);
echo json_encode(array('success' => true));
} else {
foreach($product_id as $key => $value) {
$data = array('selected_size' => $selected_size[$key],
'product_id' => $value,
'product_name' => $product_name[$key],
'product_color' => $product_color[$key],
'cookie_id' => $cookie_id,
'is_paid' => 'No');
} $this->db->insert('default_cart_temp', $data);
}
Frontend:
selected_size = $('.selected_size1').text();
arr1 = selected_size.split(".");
ss1 = arr1.slice(0, -1);
product_id = $('.product_id1').text();
arr2 = product_id.split(".");
ss2 = arr2.slice(0, -1);
product_name = $('.product_name1').text();
arr3 = product_name.split(".");
ss3 = arr3.slice(0, -1);
product_color = $('.product_color1').text();
arr4 = product_color.split(".");
ss4 = arr4.slice(0, -1);
$.ajax({
type: "POST",
dataType: "JSON",
url: "<?=base_url()?>index.php/products/products/new_instance",
data: { selected_size: ss1, product_id: ss2, product_name: ss3, product_color: ss4 },
json: {success: true},
success: function(data) {
if(data.success == true) {
alert("True");
}
}
});
In every foreach loop execution you are overriding $data and $data1 variables. You have to change them to arrays and add data like this $data[] = $subArray.

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