Insert jQuery repeater row in PHP database - php

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);
}

Related

How can I delete last all transaction that made by PHP api?

I have Receipt API that generate Receipt. While generating receipt several SQL operation is being done. Now if I generate receipt by mistake how can Undo all last operation.
What I need to do is I want all data as it is before this API call. I have some Idea about Rollback but I don't know how can I use this in this. If you help please do so.
My receipt look like this.
<?php
include 'connection.php';
extract($_REQUEST);
$data = array();
$resArr = array();
$payment_type = $_POST['payment_type'];
$cheque_date = $_POST['cheque_date'];
$cheque_no = $_POST['cheque_no'];
$paid_amount = $_POST['paid_amount'];
$query = customSelectQuery(
"SELECT c.emi_amount as customer_emi_amount, ltc.no_of_month as ltc_no_of_month,
ltc.emi_date as ltc_emi_date, ltc.loan_amount as ltc_loan_amount
from loan_to_customer ltc
LEFT JOIN customer c ON c.customer_id = ltc.customer_id
WHERE ltc.customer_id = $customer_id");
// print_r($query);
if (isset($query)) {
$ltc_data = array();
foreach ($query as $row) {
$ltc_data = array(
'ltc_emi_date' => explode(',', $row['ltc_emi_date']),
'ltc_no_of_month' => $row['ltc_no_of_month'],
'ltc_loan_amount' => $row['ltc_loan_amount'],
'customer_emi_amount' => $row['customer_emi_amount']
);
}
}
$ltc_loan_amount = $ltc_data['ltc_loan_amount'];
$remaining_loan_amount = $ltc_loan_amount - $paid_amount;
$receipt_number = 'CMF/EMI/RECEIPT/126';
$receipt_data = array(
'customer_id' => $customer_id,
'payment_type' => $payment_type,
'cheque_date' => $cheque_date,
'cheque_no' => $cheque_no,
'paid_amount' => $paid_amount,
'remain_amount' => $remaining_loan_amount,
'receipt_no' => $receipt_number
);
$insert_in_reciept = insert("receipt", $receipt_data);
$removed_emi_date = array_shift($ltc_data['ltc_emi_date']);
$number_of_month_remaining = count($ltc_data['ltc_emi_date']);
$string_number_of_month_remaining = implode(',', $ltc_data['ltc_emi_date']);
$loan_to_customer_data = array(
'customer_id' => $customer_id,
'loan_amount' => $remaining_loan_amount,
'no_of_month' => $number_of_month_remaining,
'emi_date' => $string_number_of_month_remaining
);
$update_ltc = update("loan_to_customer", $loan_to_customer_data, 'customer_id = ' . $customer_id);
$query1 = customSelectQuery("select r.*, ltc.emi_date as ltc_emi_date, ltc.*, c.first_name,
c.middle_name, c.last_name, c.gender, c.cust_address, c.cust_city,
c.cust_dist, c.cust_state, c.cust_pincode FROM receipt r
LEFT JOIN customer c ON c.customer_id = r.customer_id
LEFT JOIN loan_to_customer ltc ON r.customer_id = ltc.customer_id
WHERE r.customer_id = $customer_id");
if (isset($query1)) {
$d = array();
foreach ($query1 as $row) {
$d = array(
'first_name' => $row['first_name'],
'middle_name' => $row['middle_name'],
'last_name' => $row['last_name'],
'gender' => $row['gender'],
'cust_address' => $row['cust_address'],
'cust_city' => $row['cust_city'],
'cust_state' => $row['cust_state'],
'cust_pincode' => $row['cust_pincode'],
'ltc_emi_date' => explode(',', $row['ltc_emi_date']),
'payment_type' => $row['payment_type'],
'cheque_date' => $row['cheque_date'],
'cheque_no' => $row['cheque_no'],
'paid_amount' => $row['paid_amount'],
'remain_amount' => $row['remain_amount'],
'penalty_amount' => $row['penalty_amount'],
'receipt_no' => $row['receipt_no'],
'emi_date' => $row['emi_date'],
'pending_penalty' => $row['pending_penalty'],
'paid_penalty' => $row['paid_penalty'],
'user' => $row['user'],
'user_branch' => $row['user_branch'],
'verify' => $row['verify'],
);
}
}
$resArr = array("success" => 1, "data" => $d, "message" => "");
header('Content-Type: application/json');
echo str_replace("\/", "/", json_encode($resArr, JSON_UNESCAPED_UNICODE));
?>
Of course, it is not possible to use transactions for a scenario like this.
And there is no reliable way to undo the previous operation with a database structure like this either.
To make it possible you must normalize your database. In other words any addition must be done by means of INSERT queries only but not a single UPDATE should to be used.
Given that, to undo the operation you need to collect all the insert ids from insert queries and store them in a session. After hitting the undo button simply delete the records based on the stored ids
First, start a transaction by using the START TRANSACTION statement.
Perform whatever you want.
Finally, commit the transaction using the COMMIT statement to save data.
If you don't want to change roll back the current transaction and cancel its changes, you use the ROLLBACK statement.
Refer below link for more information.
https://dev.mysql.com/doc/refman/8.0/en/innodb-autocommit-commit-rollback.html
You can do something like this:
mysqli_begin_transaction($connection, MYSQLI_TRANS_START_READ_ONLY);
try {
mysqli_query($connection, $yourSelectQuery1);
mysqli_query($connection, $yourSelectQuery2);
mysqli_query($connection, $yourSelectQuery3);
mysqli_commit($connection);
} catch($e) {
mysqli_rollback($connection);
}
mysqli_close($connection);

How to split two array and pass to ajax using Jquery?

I am getting an error while inserting into my database.
Its showing column ARRAY. How to fix it? Instead of that I want to pass all dates (showing in the screenshot only dates in the date column)
I want to know in code where I did mistake. Why the array is coming like this?
PHP MODAL
$data_jobschedule = array(
'jobschedule_id' => $jobschedule_id,
'Activity_area_id' => $Activity_area_id,
'Contract_id' => $this->input->post('getcontract_id'),
'job_freq_id' => $this->input->post('getcontractbranch_freq'),
'job_schedule_dates' => $this->input->post('getschedule'),
//'job_schedule_frequency' => $this->input->post('getjob_schedule_frequency'),
'created_at' =>$created_Dt
);
$insert_id = 0;
if ($this->db->insert("activity_area", $data)) { //AM INSERTING ANOTHER RECORD ALSO TO DIFFERENT TABLE
$this->db->insert('job_schedule', $data_jobschedule); //HERE IS THE TABLE I NEED TO ADD DATES AND FREQUENCY
$insert_id = $this->db->insert_id();
}
so your post data is an array, you need looping through it.
on your php model, try change this
$data_jobschedule = array(
'jobschedule_id' => $jobschedule_id,
'Activity_area_id' => $Activity_area_id,
'Contract_id' => $this->input->post('getcontract_id'),
'job_freq_id' => $this->input->post('getcontractbranch_freq'),
'job_schedule_dates' => $this->input->post('getschedule'),
//'job_schedule_frequency' => $this->input->post('getjob_schedule_frequency'),
'created_at' =>$created_Dt
);
$insert_id = 0;
if ($this->db->insert("activity_area", $data)) { //AM INSERTING ANOTHER RECORD ALSO TO DIFFERENT TABLE
$this->db->insert('job_schedule', $data_jobschedule); //HERE IS THE TABLE I NEED TO ADD DATES AND FREQUENCY
$insert_id = $this->db->insert_id();
}
to
$insert_id = 0;
if ($this->db->insert("activity_area", $data)) { //AM INSERTING ANOTHER RECORD ALSO TO DIFFERENT TABLE
if (is_array($this->input->post('getschedule'))) {
foreach($this->input->post('getschedule') as $value) {
$this->db->insert('job_schedule', array(
'jobschedule_id' => $jobschedule_id,
'Activity_area_id' => $Activity_area_id,
'Contract_id' => $this->input->post('getcontract_id'),
'job_freq_id' => $this->input->post('getcontractbranch_freq'),
'job_schedule_dates' => $value[0], //assume array form like your screenshot
'job_schedule_frequency' => $value[1],
'created_at' =>$created_Dt
));
}
$insert_id = $this->db->insert_id();
}
}

PHP & sqlsrv - create array from results, without knowing column names?

Using the below, I echo a JSON array of the results. But this requires that I identify the column names which I'd like to return from the SQL query:
$new_sql = "SELECT TOP 200 * FROM STracker ORDER BY [ID] DESC";
$check_statement = sqlsrv_query($conn, $new_sql);
$data = array();
while($row = sqlsrv_fetch_array($check_statement, SQLSRV_FETCH_ASSOC)) {
$data['data'][] = array(
'id' => $row['ID'],
's_reference' => $row['s_reference'],
'reference' => $row['reference'],
'customer_name' => $row['customer_name']
);
}
Is there any way to create that array information, but return all of the columns returned by the query dynamically? So by using SELECT * FROM, all of the column data is returned in the array but without me needing to write out all of these individually? (the below)
'id' => $row['ID'],
's_reference' => $row['s_reference'],
'reference' => $row['reference'],
'customer_name' => $row['customer_name']
Ok I forgot to add that I'd tried this:
$data['data'][] = array($row);
Which is clearly wrong, and after using the following, it works perfectly!
$data['data'][] = $row;

Cannot autocomplete other textfields using CJuiAutoComplete

I have a model that has fields id_peg, nama_peg, and jabatan_peg. So here's what I wanna do:
Autosuggestion that shows the list ofid_peg as I type in the text field id_peg
When I select the suggested id_peg, the fields nama_peg and jabatan_peg are autocompleted based on that corresponding selected value (retrieved from database)
I've been trying to do the first one and I did it. But I'm stuck at the second one.
This is what I did:
view/melaporkan.php:
$this->widget('zii.widgets.jui.CJuiAutoComplete', array(
'name' => 'test1',
'source' => $this->createUrl('search'),
// additional javascript options for the autocomplete plugin
'options' => array(
'showAnim' => 'fold',
'select' => 'js:function(event, ui) {
$('#nama_peg').val(ui.item.nama_peg);
$('#jabatan_peg').val(ui.item.jabatan_peg);
}',
),
));
controllers/sitecontroller.php
public function actionSearch() {
$res = array(0 => array('id' => 1, 'value' => "id_peg"), 1 => array('id' => 2, 'value' => "jabatan_peg"), 2 => array('id' => 2, 'value' => "nama_peg"));
if (isset($_GET['term'])) {
$qtxt = "SELECT id_peg FROM pegawai WHERE id_peg LIKE :id_peg";
$command = Yii::app()->db->createCommand($qtxt);
$command->bindValue(":id_peg", '%' . $_GET['term'] . '%', PDO::PARAM_STR);
$res = $command->queryColumn();
}
echo CJSON::encode($res);
Yii::app()->end();
}
All it did was autosuggest for id_peg. When clicked some random id_peg, nama_peg and jabatan_peg were still empty.
What did I do wrong?
Actually the problem is controllers/sitecontroller.php page.
You are sending only id_peg as JSON format but trying to get as ui.item.jabatan_peg.
It is always better to send your value as
[{"id":"Caprimulgus europaeus","value":"European Nightjar"}] pattern
and get the value ui.item.value at your select function.

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

Categories