Update db tables of only updated fields of form- JQuery, PhP - php

I have a huge multistep form with data for multiple tables in mysql db. For every field my html is like-
input type="text" name="names" value="" // value set using php echo
On submit at php I am doing this for all the fields of my form-
$name=$_POST['names'] ?? ' '
to avoid unidentified index and unidentified variable
Then i update my first table and write log that its updated.
$query=mysqli_query($con,"UPDATE teacherpersonal set name='$name' ... where id=$id");
write_mysql_log("teacherpersonal updated", "facultydetails", $id).
I have defined write_mysql_log.
And similarly i update all the remaining tables with either the updated values or blank ("") values.
Since you can see that update query always executes even if the fields are not changed. Hence it is always logged that the tables are updated. But that's not what I want. I want to update only those fields in the table which are changed and remaining stay intact and log only those tables which are thus updated. Many tables won't be updated this way as the user might change only few details.
Using jquery and php.
My write_mysql_log is
function write_mysql_log($message, $db, $faculty_id)
{
$con=mysqli_connect("localhost","root","");
mysqli_select_db($con,"facultydetails");
// Construct query
$sql = "INSERT INTO my_log (message, faculty_id) VALUES('$message', '$faculty_id')";
$query=mysqli_query($con, $sql);
// Execute query and save data
if($query) {
echo 'written to the database';
}
else {
echo 'Unable to write to the database';
}
}

This you can achieve in 2 different ways.
1) With the help of jQuery check the values which are updated, post only those values to the php script
2)At the time of updating the check the current values with the updated one based on that criteria update the db tables.
solution 1 is less time taking process compare to the other.

You need to update only the user edited value, by doing this you can achieve it;
$oldvalue = array("username" => "green", "email" => "green#mail.com","dob" => "111");
$newvalue = array( "email" => "green#mail.com","dob" => "111","username" => "blue");
$updates = array_diff($newvalue, $oldvalue);
$implodeArray = implode(', ', $updates);
$sql = ("UPDATE user WHERE userID=$userID SET $implodeArray");
mysql_query($sql,$this->_db) or die(mysql_error());
mysql_close();
Output:
$updates = array_diff($newvalue, $oldvalue);
will have:
Array ( [username] => blue )
which is changed one

Ok after considering many options like-
create json object for old and new data and then compare and check which values changed and update that table and log it.
Or create a php array with old and new data and check diff then do the same (as suggested by Ram Karuppaiah)
Or a bad idea to have a flag on every input and then mark which ones have changed using onkeyup jquery event then try to update only those fields tables.
So finally what i did is that i let the form get submitted with all the data. As earlier i am taking the data in php as $name=$_POST['names'] ?? ' ' (blank if nothing is submitted or if something submitted then its value).
Before update statement in php, i am querying the table and comparing the database values with the values i got, if all same i dont do anything. If not then i update the table with the new values and log the change.

Related

How to make skip to any empty column when update data by php file to MySQL

I have file PHP by this file I update the data in MySQL table. I send data to this PHP file from flutter app but there are one problem I have 3 field in this file so user can update data in those 3 Column in MySQL table to here every thing is ok but my problem if user send just one Column data from flutter app to PHP file the data will update in this Column but the others Column will will become null.
So how I can make this file make skip to any empty column the user not send data to it?
I need the old data not be changed in the database if the file does not get new data for that column.
Thank you.
PHP file:
<?php
require_once 'con.php';
$id = $_POST['id '];
$IDbook= $_POST['IDbook'];
$IDbookset= $_POST['IDbookset'];
$sql="UPDATE topics SET IDbook= ? ,IDbookset=? WHERE id=?";
$stmt = $con->prepare($sql);
$stmt->bind_param("sss",$IDbook,$IDbookset,$id);
$stmt->execute();
$result = $stmt->get_result();
$exeQuery = mysqli_query($con, $sql) ;
if($exeQuery){
echo (json_encode(array('code' =>1, 'message' => 'Modifier avec succee')));
}else {echo(json_encode(array('code' =>2, 'message' => 'Modification Non Terminer')));
}
?>
One way to do it is to
Fetch the data for the current $id say into $OldIdbook and $OldIdbookset
get updated values like this $IDbook= $_POST['IDbook'] ?? $oldIDbook; This uses the old value if the $_POST is null.
then execute the query to update.
The second way is to construct the query by adding only the field=value pairs that have changed to the query. Its a little bit more work to handle the comma.

How to get the value of item POST in JForm after submit?

I am currently constructing a component in Joomla and I have to get the values of the form field that user submitted. After that, I have to insert the values into database. The problem is that I just able to insert the $inventory_id but I can't get the value of the form field. Thank you.
<?php
$input = JFactory::getApplication()->input;
$formData = new JRegistry($input->get('jform', '', 'array'));
$name = $formData->get('inventory_name', 'test');
$leadtime = $formData->get('leadtime', null);
$max_lead = $formData->get('max_lead', null);
$daily_usage = $formData->get('daily_usage', null);
$max_usage = $formData->get('max_usage', null);
//formula to calculate reorder point
$lead_time_demand = $leadtime * $daily_usage;
$safety_stock = ($max_usage * $max_lead) - ($daily_usage * $leadtime);
$reorder_point = $lead_time_demand + $safety_stock;
if (empty($this->item->id)){ //For new added item
$inventory_id = $row['AUTO_INCREMENT'];
$sql_new = "INSERT INTO wer_reorder_point_list (inventory_id, inventory_name, reorder_point)
VALUES ('$inventory_id', '$name', '$reorder_point');";
mysqli_query($con,$sql_new);
}
?>
You never declare $row in this code, so what is $inventory_id = $row['AUTO_INCREMENT']; supposed to do?
If your database is configured to autoincrement inventory_id, then you don't need that column in the insert statement. So you could do this:
$sql_new = "INSERT INTO wer_reorder_point_list (inventory_name, reorder_point)
VALUES ('$name', '$reorder_point');";
and it will automatically fill that column with the next integer.
By the way, you should also use prepared statements, especially since you have user input, which could be a security problem.
You don't insert an autoincremented id directly using the form data, you let the database take care of that. If you tried to insert it you could easily end up with a race condition given that in a web application such as Joomla there could be many users attempting to insert new lines with the same id at the same time. This is why your form does not contain an inventory_id value.
If you want to pass a hidden ( from the user) value to the POST you need to include a hidden field with that value in your form. However, as stated in the first paragraph, you would not use that for a unique ID.

If multiple hardware not found, delete all values from list

I am trying to do the following:
If ID is not found inside the array 'hardware', delete all values where ID doesn't exist from the hardware array.
The issue I encountered is that, where I am able to delete one value at a time using the following:
foreach ($this->hardware AS $hardware){
if(!in_array($hardware['ID'],$hardwareList)){ // checks if hardware id is not on the hardware list
$query = 'DELETE FROM hardware_map WHERE ID='.$hardware['ID'];
$db->setQuery( $query );
$result = $db->loadResult();
}
}
It will not remove multiple values, if I delete all of them at once inside the textarea field.
<textarea id="hardwareTextArea" name="hardwareTextArea"><?php
foreach($this->hardware AS $hardware){
echo $hardware['name']."\n";
?></textarea>
Any help is appreciated on how to delete multiple values from the list at once if I delete all the values from the textarea.
You can first find the IDs that you want to remove them, then use one query by using IN:
DELETE FROM hardware_map WHERE ID IN (id1,id2, ...)

Update Only Changed Values to Database

I have a form that I am trying to use to track batches of beer. Because the process of brewing takes several weeks or even months, I cannot complete the form all at once. When I first create a record for a beer, most of my values are set as NULL. When I retrieve the record and attempt to update it, it also updates all my NULL values to zeros. How can I send only changed values to the database from my form so the rest will be left as NULL?
Below is a sample of my update code (please forgive any PDO transgressions - it is my first foray into using PDO).
<?php
//Connect to Database
try {
$DBH = new PDO('mysql:host=localhost; dbname=dbname', 'user', 'password');
}
catch (PDOException $e) {
echo $e->getMessage();
exit();
}
//Build Update SQL Query
$update = "UPDATE brewlog
SET
BrewDate = :BrewDate,
EndOfPrimary = :EndOfPrimary,
EndOfSecondary = :EndOfSecondary,
PackagingDate = :PackagingDate,
AnticipatedOG = :AnticipatedOG,
WHERE ID = :ID";
//Prepare Query, Bind Parameters, Excute Query
$STH = $DBH->prepare($update);
$STH->bindParam(':ID', $_POST['ID'],PDO::PARAM_INT);
$STH->bindParam(':BrewDate', $_POST['BrewDate'],PDO::PARAM_STR,10);
$STH->bindParam(':EndOfPrimary', $_POST['EndOfPrimary'],PDO::PARAM_STR,10);
$STH->bindParam(':EndOfSecondary', $_POST['EndOfSecondary'],PDO::PARAM_STR,10);
$STH->bindParam(':PackagingDate', $_POST['PackagingDate'],PDO::PARAM_STR,10);
$STH->bindParam(':AnticipatedOG', $_POST['AnticipatedOG'],PDO::PARAM_INT);
$STH->execute();
?>
You would want to validate your data before you bind it. Say something like
if(!empty($_POST['EndOfPrimary'])) {
$eop = $_POST['EndOfPrimary'];
} else {
$eop = NULL;
}
Then bind
$STH->bindParam(':EndOfPrimary', $eop,PDO::PARAM_STR,10);
Edit:
You would also use this validation to check more than if the field was left blank. It looks like you probably want a date to be entered, so perhaps your would check if the user actually entered a date, and if not then send them back to the form with some type of helpful message about where they made the mistake. This is the regexp I use to validate a date.
function pcre_date($subject) {
return preg_match('/^[0-9]{1,2}\/[0-9]{1,2}\/[0-9]{4}$/', $subject);
/*
* matches 01/01/1984, 1/1/1984, but NOT 1/1/84
* wants mm/dd/yyyy
*/
} // returns 0 for non valid, 1 for valid
Then I would use this for the validation
if(!empty($_POST['EndOfPrimary'])) {
if(pcre_date($_POST['EndOfPrimary'])) {
$eop = $_POST['EndOfPrimary'];
} else {
$form_errors[] = "Please format date as mm/dd/yyyy.";
}
} else {
$eop = NULL;
}
To accomplish this cleanly, use two steps:
In the form presented to the user, maintain a list of changed fields. For example, when a user modifies the data in an input field, use Javascript to copy the contents of that field into a hidden form to be submitted. Then when the user clicks "submit", send only the contents of the hidden form, not the contents of the original form with all fields.
In your PHP script, build your query based on the fields provided. Your query will now include only the fields that were modified. This way, when you perform your UPDATE statement, the unchanged fields will be untouched.
Sorry george, I guess you are way far complicated of what he is trying to do.
Actually, when you use _POST['somevar'], if the field is blank, you get and EMPTY string.
and the empty string is saved to the database so the field is not NULL anymore
The simplest way to ensure the fields stay NULL in the database if there is no value captured is:
$STH->bindParam(':EndOfPrimary', isset($_POST['EndOfPrimary'])?$_POST['EndOfPrimary']:null ,PDO::PARAM_STR,10);

How to insert entries into different tables from one page?

I have 4 tables named wheels, tires, oil_change, other_servicing.
Now, I have an order form for the person that comes for a car checkup. I want to have all of these 4 options in a form. So say someone comes for new wheels but not for tires, oil change, and other servicing and they will leave the other fields blank. And then you might have a scenario where all four fields are filled up. So how do i submit each to their respective tables from that one form?
The form will submit to a single php script. In the php you must do 4 separate queries to put the data into the correct tables. For example if you have this in php:
$wheels = $_REQUEST['wheels'];
$tires = $_REQUEST['tires'];
$oil_ch = $_REQUEST['oil_change'];
$other = $_REQUEST['other_servicing'];
mysql_query("INSERT INTO wheels (wheels) VALUES $wheels");
mysql_query("INSERT INTO tires (tires) VALUES $tires");
mysql_query("INSERT INTO oil_change (oil_change) VALUES $oil_ch");
mysql_query("INSERT INTO other_servicing (other_servicing) VALUES $other");
Of course I don't know the schemas of your tables but this is just an example of how you have to split it into 4 queries.
However, I would suggest to you that rather than have 4 tables for this, just have one table and make each of these a column instead. There may be other details I don't know about which would necessitate separate tables but with the info you have given seems like it would be simpler.
This shouldn't present any problem. The PHP page that receives the form data can run as many queries as you want. The skeleton for the code would be something like:
if($_POST['wheels']) { //if they filled in the field for wheels...
mysql_query("insert into wheels...");
}
if($_POST['tires']) { //if they filled in the field for tires...
mysql_query("insert into tires...");
}
if($_POST['oil_change']) { //if they filled in the field for oil_change...
mysql_query("insert into oil_change...");
}
... etc
for each form you would have something like this:
if($_POST['wheels']){mysql_query("INSERT INTO wheel_table (column1) VALUES (" . 'mysql_real_escape_string($_POST['wheels']) . "')")
this checks if the form element has been set, or has a value, and if it does, it creates a new row in the corresponding table.
if the form element's name is not 'wheels', you'll have the change $_POST['wheels'] to $_POST['form_element_name'] and if the table's name is not wheel_table, you'll have to change that and same with the column name.
this all has to be wrapped in a
In the form action you will specify the php file that will process the form.
In the php script file you will make tests of what parts of the forms are used and inserted in the respective table.
Try to separate the tests and the inserts of each table, to be easier for you.
This could be useful
if(isset($_POST['submit'])) // assuming you have submit button with name 'submit'
{
$fields['wheels'] = isset($_POST['wheels']) ? $_POST['wheels'] : null;
$fields['tires'] = isset($_POST['tires']) ? $_POST['tires'] : null;
$fields['oil_change'] = isset($_POST['oil_change']) ? $_POST['oil_change'] : null;
$fields['other_servicing'] = isset($_POST['other_servicing']) ? $_POST['other_servicing'] : null;
$q="";
foreach($fieldsas $key=>$val)
{
if($val!==null)
{
$q="insert into ".$key." values('".mysql_real_escape_string($val)."')";
mysql_query($q);
}
}
if($q==="") echo " Please fill up at least one field !";
}
This is just the core idea, using this you can execute multiple queries if user submits more than one fields at once and you may have to add other values (i.e. user_id).

Categories