Update data array in the same row - php

I would like to approve leave application based on dates for example as below :
echo "<select name='app_status[]' required>
<option value='' selected>Pending</option>
<option value='1'>Approve</option>
<option value='2'>Reject</option></select>";
$app_status = array();
if(is_array($app_status)) {
foreach($_POST['app_status'] as $key1=>$value1) {
$app_status[]=$value1;
}
}
for($loop = 0; $loop < count($app_status); $loop++) {
if($app_status[$loop]=="" || $app_status[$loop]==null)
$error=1;
}
if(isset($error))
$error=1;
else
$error=0;
if($error==0) {
for ($i = 0; $i < count($app_status); $i++) {
$str = $app_status[$i];
$sql= "UPDATE leaves_apply SET app_status ='$str' WHERE app_id='$app_id'";
$query2 = mysqli_query($sql);
}
}
For example if I approve the leaves for 12/8/2017 - 15/8/2017 except for 16/8/2017, I will get an output like this 11112 And when I check the database, the column app_status will only update 2, as if it only read the last data and not the first four data. If possible I would like the data 11112 to be update in the app_status column for app_id no 1357. I'm not sure if this is the right way, please help me as I'm new to this. Thank you.

I think this modification should do what you would like...
if($error==0) {
// Declare the string for the app_status
$str = "";
// Loop though the statuses and put together the statuses
for ($i = 0; $i < count($app_status); $i++) {
$str .= $app_status[$i];
}
// Update the database record
$sql= "UPDATE leaves_apply SET app_status = '$str' WHERE app_id='$app_id'";
$query2 = mysqli_query($sql);
}
Please remember to escape your database queries to prevent SQL injection.

Related

Is there a way to update 12000+ rows from txt file in less then 2mins?

I need to update a table with more then 12000 row using php Codeigniter and a txt file.. reading the file and the foreach loop are fine but when updating line by line it takes like 30 mins, I guess the problem is I'm searching by name because I have no id in the txt file...
Here is my code:
controller:
$fn = fopen($this->upload->data('full_path'),"r");
$update = true;
while(! feof($fn) && $update) {
$pieces = explode("|", fgets($fn));
if(sizeof($pieces) == 9 && is_numeric(trim($pieces[1]))) {
$update = $this->model_products->update3s($pieces);
}
}
fclose($fn);
Model:
public function update3s($product) {
if ($product) {
$product[2] = trim(str_replace("'","''",$product[2]));
$product[1] = trim($product[1]);
$product[6] = trim($product[6]);
$product[3] = trim($product[3]);
$sql = "UPDATE products set qty = $product[3], price_vente = $product[6] where (name = '$product[2]')";
echo $sql.'<br>';
$update = $query = $this->db->query($sql);
return $update;
}
return false;
}
You can use transaction and add index for column name in database table.
$fn = fopen($this->upload->data('full_path'),"r");
$update = true;
$updatedCount = 0;
while(! feof($fn) && $update) {
$pieces = explode("|", fgets($fn));
if(sizeof($pieces) == 9 && is_numeric(trim($pieces[1]))) {
if ($updatedCount == 0) {
$databaseInstance->beginTransaction();
}
$update = $this->model_products->update3s($pieces);
++$updatedCount;
if ($updatedCount > 500) { //in one transaction update 500 rows
$databaseInstance->commit();
$updatedCount = 0;
}
}
}
if ($updatedCount > 0) { // if we have not commited transaction
$databaseInstance->commit();
}
fclose($fn);
Some tips
Add index to field name
Use prepared statements
Disable the MySQL forgeign key check Read more
writing sql function can do that even in much lesser time .
using feature like :
REPLACE()
cursors
SPLIT_STRING(custom)
in a mysql user defined function
CREATE FUNCTION update3s(hole_file_content LONGTEXT) RETURNS Boolean
BEGIN
-----Your implementation(same logic in sql ) ------
END
then coll it just by if it is CI 3
$this->db->call_function('update3s', file_get_contents($this->upload->data('full_path')));
else
$this->db->query("select update3s(".file_get_contents($this->upload->data('full_path')).")");

Same serial number is generating for different requests

I am inserting a serial number in a table that is increment by one always but when multiple request is coming in same time it is inserting same serial number for different requests.I am using mysql database.
I know i am fetching the max serial number too early in the code and if request is come in same time so it will fetching same serial number for both. is it good idea to update serial number after all work done. what if inserting a record for new request and updating the serial number for previous one is in same time.
public function add(){
$session = $this->request->session();
$company_id = $session->read('Admin.company_id');
$emp_id = $session->read('Admin.emp_id');
$user_email_id = $session->read('Admin.email_id');
$employee_name = $session->read('Admin.employee_name');
$conn = ConnectionManager::get('default');
if ($this->request->is('post')) {
try{
$conn->begin();
$department = $this->request->data['department'];
$data = $this->request->data;
if(!array_key_exists('is_requisition_for_contractor', $data)){
$is_requisition_for_contractor = 0;
} else {
$is_requisition_for_contractor = $data['is_requisition_for_contractor'];
}
if(!array_key_exists('is_requisition_for_employee', $data)){
$is_requisition_for_employee = 0;
} else {
$is_requisition_for_employee = $data['is_requisition_for_employee'];
}
if(!array_key_exists('is_boulder_requisition', $data)){
$is_requisition_for_boulder = 0;
} else {
if($data['is_boulder_requisition'] == ''){
$is_requisition_for_boulder = 0;
} else {
$is_requisition_for_boulder = $data['is_boulder_requisition'];
}
}
$is_requisition_for_plant = 0;
if(!array_key_exists('is_plant_requisition', $data)){
$is_requisition_for_plant = 0;
} else {
if($data['is_plant_requisition'] == ''){
$is_requisition_for_plant = 0;
} else {
$is_requisition_for_plant = $data['is_plant_requisition'];
}
}
if(array_key_exists("files",$this->request->data)) {
$files = $this->request->data['files'];
if (count($files)) {
$files_uploading_response = $this->uploadMultipleFiles($files, 'files/requisitions/');
}
}
$last_material_insert_id = '';
if($this->request->data('material_id')[0] == ''){
if($this->request->data('department') == 1){
$type = 1;
} elseif($this->request->data('department') == 3){
$type = 3;
} elseif($this->request->data('department') == 2){
$type = 2;
}
if($this->request->data('department') == 1 || $this->request->data('department') == 3){
$conn->execute("INSERT INTO material (material_name, material_type_id, company_id, status, is_approved_by_admin) VALUES (?,?,?,?,?)",[$this->request->data('material_name'), $type, $company_id, 1,0]);
$last_material_insert_id = $conn->execute("SELECT LAST_INSERT_ID() AS last_id")->fetchAll('assoc');
} elseif($this->request->data('department') == 2) {
//todo for unapproved material
$conn->execute("INSERT INTO material (part_no, material_type_id, company_id, status, is_approved_by_admin,unique_category_id) VALUES (?,?,?,?,?,?)",[$this->request->data('part_no')[0], $type, $company_id, 1,0,$this->request->data('unique_category_id')[0]]);
$last_material_insert_id = $conn->execute("SELECT LAST_INSERT_ID() AS last_id")->fetchAll('assoc');
}
}
// here i am fatching max serial number from table
$requistion_number = $conn->execute("SELECT IF(MAX(requisition_no) IS NULL, 0,MAX(requisition_no)) AS requisition_no FROM requisition WHERE site_id = ?",[$this->request->data('site_id')])->fetchAll('assoc');
$Requisition = TableRegistry::get('requisition');
$requisition = $Requisition->newEntity();
$requisition->registered_on = $this->request->data['date'];
$requisition->department_id = $this->request->data('department');
$requisition->site_id = $this->request->data('site_id');
$requisition->issues_to_id = $this->request->data['prepared_by_id'];
$requisition->prepared_by_id = $this->request->data['prepared_by_id'];
$requisition->approved_by_id = $this->request->data['hod_id'];
$requisition->hod_id = $this->request->data['hod_id'];
$requisition->is_diesel_requisition_for_employee = $is_requisition_for_employee;
$requisition->is_diesel_requisition_for_contractor = $is_requisition_for_contractor;
$requisition->is_requisition_for_boulder = $is_requisition_for_boulder;
$requisition->is_requisition_for_plant = $is_requisition_for_plant;
if(array_key_exists('for_tanker_stock', $this->request->data)) {
$requisition->for_tanker_stock = 1;
}
if($last_material_insert_id != ''){
$requisition->is_material_approved_by_admin = 0;
}
$requisition->status = 1;
$site_id = $this->request->data['site_id'];
$requisition->requisition_no = $requistion_number[0]['requisition_no'] + 1;
$requistionnumber = $requistion_number[0]['requisition_no'] + 1;
$saveRequsition = $Requisition->save($requisition);
$conn->commit();
}
I am expecting the output different serial number for each request.any optimise way to do this. thanks in advance.
Ok, how about the same strategy, setting the $requisition_number after the row has been inserted (see my other answer), but using a single query with the same method you use to determine the new requisition id:
$conn->execute("UPDATE requisition
SET requisition_no = (SELECT IF(MAX(requisition_no) IS NULL, 0,MAX(requisition_no)) AS requisition_no FROM requisition WHERE site_id = ?) + 1",
[$this->request->data('site_id')]);
The idea here is that a single query will be executed in one step, without another, similar query, being able to interfere.
What you currently do is to first get the old requistion number like this:
$requistion_number = $conn->execute("SELECT IF(MAX(requisition_no) IS NULL, 0,MAX(requisition_no)) AS requisition_no
FROM requisition WHERE site_id = ?",[$this->request->data('site_id')])->fetchAll('assoc');
and then increase it before you save and commit.
My suggestion is to not set the $requistion_number at all before you save and commit the requisition row, but to determine the $requistion_number afterwards.
You now wonder how?
Well, you need to count the total number of requisition rows in the table for the site the requisition is for, and add one, like this:
$last_requisition_id = $conn->execute("SELECT LAST_INSERT_ID() AS last_id")->fetchAll('assoc');
$site_id = $this->request->data('site_id');
$requisition_number = $conn->execute("SELECT COUNT(*) AS requisitionsCount
FROM requisition
WHERE <primary_key> <= ? AND
site_id = ?",
[$last_requisition_id, $site_id]) + 1;
$conn->execute("UPDATE requisition
SET requisition_no = ?
WHERE <primary_key> <= ?",
[$requisition_number, $last_requisition_id]);
I know this code is not working. The $requisition_number will probably contain an array with the requisitionsCount as a value, but you can correct that.
Because you're using data that is already present in the database table you don't run the risk that two rows will get the same $requisition_number. The assumption here is that requisitions are never deleted.

is there any possible chance when i input data into loop and doesnt entered into database?

sorry for my bad english . i got problem with looping . my friend said when he used my program and he insert 20 data or more into database in one time , sometimes a data doesnt match with data previously entered .
an example : he insert 20 data and he just got 19 but the problem is that happening sometimes.
so im confused now , how can the program error just sometimes ?
here my code :
else if ($mod == 'suratkeluar'){
$batas = $_GET['batas'];
if (isset($_POST['submit'])) {
for ($i = 0; $i < $batas; $i++) {
$idlot = $_POST['hiddenlot'][$i];
$idbenang = $_POST['hiddenbenang'][$i];
$benang = $_POST['jenisbenang'][$i];
$warna = $_POST['warna'][$i];
$lot = $_POST['lot'][$i];
$harga = $_POST['hiddenprice'][$i];
$netto = $_POST['netto'][$i];
$box = $_POST['box'][$i];
$cones = $_POST['cones'][$i];
$ket = $_POST['keterangan'][$i];
$cussplit = explode('_',$_POST['customer']);
$idcus = $cussplit[0];
$cus = $cussplit[1];
$alamatcus = $cussplit[2];
$kota = $cussplit[3];
$POsplit = explode('_',$_POST['nopo']);
$idpo=$POsplit[0];
$nopo=$POsplit[1];
$mobilsplit = explode('_',$_POST['kendaraan']);
$kendaraan = $mobilsplit[0];
$plat = $mobilsplit[1];
$identitas = $_POST['identitas'][$i];
$month = date('n');
$years=date('Y');
if($idlot != 0){
$a=mysql_query("INSERT INTO surat_jalan VALUES ('',now(),'$_POST[nosurat]','$idlot','$benang','$warna','$lot','$harga','$netto','$box','$cones','$idcus','$cus','$alamatcus','$kota','$idpo','$nopo','$ket',1,'$month$years','$identitas','$kendaraan','$plat','$idbenang')");
$aax=mysql_query("SELECT * FROM lot WHERE id_lot='$idlot'");
$xx=mysql_fetch_array($aax);
$net=$xx['netto'] - $netto;
$bbox=$xx['box'] - $box;
$ccones=$xx['cones'] - $cones;
if($net == 0)
{
$a= mysql_query("UPDATE lot SET netto = '$net',
box = '$bbox',
cones = '$ccones',
warning = 1
WHERE id_lot = '$idlot'");
}
else
{
$a=mysql_query("UPDATE lot SET netto = '$net',
box = '$bbox',
cones = '$ccones'
WHERE id_lot = '$idlot'");
}
}
$b = $i + 1;
for ($c = 0; $c < $box; $c++) {
$packinglist = $_POST["packinglist$b"][$c];
$a= mysql_query("INSERT INTO packing_list VALUES('','$packinglist','$surat[id_surat]','$surat[no_surat_jalan]')");
}
}
}
}
How about this? I'll give an example but this could go with (probably) all queries. Let's say, this one (second from the last):
$a = mysql_query("UPDATE lot SET netto = '$net', box = '$bbox', cones = '$ccones' WHERE id_lot = '$idlot'");
To check if it was successful, you can add additional lines:
if ($a) // Success?
print("Row has been updated.<br>");
else // Error
print("An error has occured; row has not been updated. Reason: ".mysql_error()."<br>");
If there are no redirections at the end, etc. and there is at least one error (the last one?), then your friend will see something like this:
An error has occured; row has not been updated. Reason: #1054 - Unknown column 'cones' in 'where clause'
An error has occured; row has not been updated. Reason: #1054 - Unknown column 'box' in 'field list'
With that help, you can see if there is an error in your queries or in application itself (timeout?).
There is also another problem: you're using PHP's mysql_API, which is deprecated. Instead, you should upgrade and use mysqli_API.

How to check a value of a variable and call different function

I have the following variables in my cart.php file:
<?php $readyTotal = $qty*price ?>;
Now I want to do is that if the $readyTotal > $1000 then call a file which is adding an item into the customer's cart.
($slq= msyql_query("INSERT into `table`.....value.....");
and if the value of $radyTotal < $1000;
dont add any extra item or if it has been added just remove it by calling the removal file.
($sql =mysql_query("DELETE from `table` where .......");
Please note that how to do this I want to call/include the files in my cart.php file. but i am unable to do this. is there any other way to do it or by using ajax/jquery which check every the value of $readyTotal every time when it changes.
function ad(){
$signature =getSignature();
$item = 21;
$type = 100;
$type= 0;
$sql2 = mysql_query("Select * From `temp` where `item`='$item' AND `price`= 0 AND
`signature`='$signature' AND `type`=0 AND `toppings`=0 " );
$count= mysql_num_rows($sql2);
if($count ==0){
$sql = mysql_query("INSERT INTO `temp`
(`item`,`price`,`signature`,`type`,`toppings`, `isCoupon`)
VALUES
('$item','$type','$signature','0','0', '1')");
}
}
function removeMe(){
mysql_query("DELETE FROM `temp` WHERE `item`=21 AND `signature`='".getSignature()."'");
}
When I try the above function individual file it works fine, but when i use both in it does not woks please.... what is wrong with this...
<?php
include_once("customfunctionfile.php");
$object = new quiz;
$readyTotal = $qty*price ;
if($readyTotal > 1000){
$object->ad();
}else{
$object->removeMe();
}
?>;
customfunctionfile.php
class quiz{
function ad(){
$signature =getSignature();
$item = 21;
$type = 100;
$type= 0;
$sql2 = mysql_query("Select * From `temp` where `item`='$item' AND `price`= 0 AND
`signature`='$signature' AND `type`=0 AND `toppings`=0 " );
$count= mysql_num_rows($sql2);
if($count ==0){
$sql = mysql_query("INSERT INTO `temp`
(`item`,`price`,`signature`,`type`,`toppings`, `isCoupon`)
VALUES
('$item','$type','$signature','0','0', '1')");
}
}
function removeMe(){
mysql_query("DELETE FROM `temp` WHERE `item`=21 AND
`signature`='".getSignature()."'");
}
}
You can achieve this something like this using functions without including file.
<?php
$readyTotal = $qty*price;
if($readyTotal > 1000) //considering amount in $
{
addItemToCart($cartDetails) // call function to add item into the cart
}
else {
removeItemFromCart($cartDetails) //call function to remove item from cart
}
?>
Define functions addItemToCart and removeItemFromCart to fire your queries.

Mysql Renaming Column In PHP

I am using a script to generate cascading dropdowns using a MySQL database.
A course is selected, then a location and from that the start date.
It has three columns: Course, Location and Start Date.
How can I rename these so that they are Course2, Location2 and Start Date2?
I have tried look for a solution but aliasing doesn't seem to work.
This is the SELECT statement:
$sql = "SELECT DISTINCT `$col` FROM `$table`".$where."ORDER BY `$col` ASC";
This is the full script I am using:
http://coursesweb.net/ajax/multiple-select-dropdown-list-ajax_t
$table = 'options';
$ar_cols = array('Course', 'Location', 'Start Date', null);
$preid = 'slo_'; // a prefix used for element's ID, in which Ajax will add <select>
$col = $ar_cols[0]; // the variable used for the column that wil be selected
$re2_html = ''; // will store the returned html code
// if there is data sent via POST, with index 'col' and 'wval'
if (isset($_POST['col']) && isset($_POST['wval'])) {
// set the $col that will be selected and the value for WHERE (delete tags and external spaces in $_POST)
$col = trim(strip_tags($_POST['col']));
$wval = "'".trim(strip_tags($_POST['wval'])).
"'";
}
$key = array_search($col, $ar_cols); // get the key associated with the value of $col in $ar_cols
$wcol = $key === 0 ? $col : $ar_cols[$key - 1]; // gets the column for the WHERE clause
$_SESSION['ar_cols'][$wcol] = isset($wval) ? $wval : $wcol; // store in SESSION the column and its value for WHERE
// gets the next element in $ar_cols (needed in the onchange() function in <select> tag)
$last_key = count($ar_cols) - 1;
$next_col = $key < $last_key ? $ar_cols[$key + 1] : '';
$conn = new mysqli($server, $user, $pass, $dbase); // connect to the MySQL database
if (mysqli_connect_errno()) {
exit('Connect failed: '.mysqli_connect_error());
} // check connection
// sets an array with data of the WHERE condition (column=value) for SELECT query
for ($i = 1; $i <= $key; $i++) {
$ar_where[] = '`'.$ar_cols[$i - 1].
'`='.$_SESSION['ar_cols'][$ar_cols[$i - 1]];
}
// define a string with the WHERE condition, and then the SELECT query
$where = isset($ar_where) ? ' WHERE '.implode($ar_where, ' AND ') : '';
$sql = "SELECT DISTINCT `$col` FROM `$table`".$where.
"ORDER BY `$col` ASC";
$result = $conn - > query($sql); // perform the query and store the result
// if the $result contains at least one row
if ($result - > num_rows > 0) {
// sets the "onchange" event, which is added in <select> tag
$onchg = $next_col !== null ? " onchange=\"ajaxReq('$next_col', this.value);\"" : '';
// sets the select tag list (and the first <option>), if it's not the last column
if ($col != $ar_cols[$last_key]) $re2_html = '<label>'.$col.
':</label> <select name="'.$col.
'"'.$onchg.
' id="'.$col2.
'"><option>Select a '.$col.
'</option>';
while ($row = $result - > fetch_assoc()) {
// if its the last column, reurns its data, else, adds data in OPTION tags
if ($col == $ar_cols[$last_key]) $re2_html. = '<br/>'.$row[$col];
else $re2_html. = '<option value="'.$row[$col].
'">'.$row[$col].
'</option>';
}
if ($col != $ar_cols[$last_key]) $re2_html. = '</select> '; // ends the Select list
} else {
$re2_html = '0 results';
}
$conn - > close();
// if the selected column, $col, is the first column in $ar_cols
if ($col == $ar_cols[0]) {
// adds html code with SPAN (or DIV for last item) where Ajax will add the select dropdown lists
// with ID in each SPAN, according to the columns added in $ar_cols
for ($i = 1; $i < count($ar_cols); $i++) {
if ($ar_cols[$i] === null) continue;
if ($i == $last_key) $re2_html. = '<p id="'.$preid.$ar_cols[$i].
'"> </p>';
else $re2_html. = '<p id="'.$preid.$ar_cols[$i].
'"> </p>';
}
// adds the columns in JS (used in removeLists() to remove the next displayed lists when makes other selects)
$re2_html. = '<script type="text/javascript">var ar_cols = '.json_encode($ar_cols).
'; var preid = "'.$preid.
'";</script>';
} else echo $re2_html;
Any help would be appreciated. I am pulling my hair out at this point! Please let me know if you need more information.
You are doing something very very weird...
I can't read your code, and I can't get your logic...
But just in case, maybe it can help you somehow:
$col2 = ''.$col.'2';
$sql = "SELECT DISTINCT `$col` as `$col2` FROM `$table`".$where."ORDER BY `$col` ASC";

Categories