I have this string response coming from the server :
string '{"code":1,"status":200,"data":
[{"connect_id":"3","equipment_id":"1","sample_id":"33","test_id":"44","message_type":"test_ordered","sent_date":"0000-00-00"},
{"connect_id":"12","equipment_id":"34","sample_id":"234","test_id":"234","message_type":"asdasd","sent_date":null}]}'
I have to update my local table's fields using the values found in "data".
In case a value coming from the response is NULL (on a particular field from "data"), there should be no changes to that field when updating the local table.
The table to be updated has many fields but let's say I want to update only the following three fields: equipment_id,sample_id,test_id.
After the update is succesfull I have to send back a response to the server telling that the transaction was succesfull and to update it's status (which is a field of the table's server from where the data has been collected to send the response) so the server won't send the response twice.
I'm assuming you're using PDO and a valid pdo-connection in variable $dbc. I assume further that you identify your rows via the connect_id. You should change this according your needs.
Following code should give you an outline how to tackle this. Please regard my comments. I doesn't have done all for you, especially omitted the error handling.
$result = json_decode($response, true);
// You should validate that the decoding was successful and
// that the result contains all the data you expect.
// You find your data as in $result['data']
// This is an (numbered) array of associative arrays with your "columns" as key
// and the data as value
// prepare your update statement
$q = $dbc->prepare('
UPDATE mytable
SET
equipment_id = ?,
sample_id = ?,
test_id = ?
WHERE
connect_id = ?
');
foreach ($result['data'] as $row) {
// and execute it while looping through the data-array with
// the appropriate data. Please note that the order of the
// parameters got to be the same as in the prepared statement
$params = array(
$row['equipment_id'],
$row['sample_id'],
$row['test_id'],
$row['connect_id']
);
$q->execute($params);
// check success of the execute too.
}
Related
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.
I have an app that is receiving sensor data. As an illustration let's say the expected range is between 0.01 and 10. In this case in the migration I may have something like:
$table->float('example',5, 2)
This way I am able to handle an order of magnitude outside the expected range. However it is possible for the sensor to glitch and send values of say 10 000. As the sensor is sending an array of values it is likely that not all the data is incorrect so it is preferred to still write the data to the DB. For the initial insert I am using the code below which is working as expected:
DB::table($tableName)->insertOrIgnore($insert_array);
However, in some circumstances the sensor can resend the data in which case the record needs to be updated. It's possible that the value(s) that are out of range can remain in the array, in which case the update statement below will throw an out of range error:
DB::table($tableName)->where('$some_id','=', $another_id)->update($insert_array);
I have not been able to find an something akin to an "updateorignore" functionality. What is the best way to handle updating this record? Note I cannot simply put it in a try catch since this table will be a parent table to some children and ignoring it will result in some orphaned entries.
Do you have some unique points of data to tie the records together, such as a timestamp or an id from the origin of the data? If so, you can use updateOrInsert
DB::table($tableName)
->updateOrInsert(
['remote_id' => $insert_array['remote_id'],
[
'example_field_1' => $insert_array['example_field_1'],
'example_field_2' => $insert_array['example_field_2'],
]
);
This is discussed at:
https://laravel.com/docs/master/queries#updates
Thanks to James Clark Developer to help me get to the solution. Below is some sample code to resolve the problem:
$values = array();
//set up values for binding to prevent SQL injection
foreach ($insert_array as $item) {
$values[] = '?';
}
//array values need to be in a "flat array"
$flat_values = implode(", ", $values);
//add in separators ` to column names
$columns = implode("`, `",array_keys($insert_array));
//write sql statement
$sql = "INSERT IGNORE INTO `example_table` (`$columns`) VALUES
($flat_values) ON DUPLICATE KEY UPDATE id = '$id'";
DB::insert($sql, array_values($insert_array));
}
I am working on an android app which uses APIs made with php. Here, i am dynamically creating columns and their values.
I am verifying the API via postman and a strange thing happens every time, While looping through the Json Object what i am doing is first creating column and then inserting its values.
The problem is only the 1st iteration saves the element and rest of them only creates the column but does not insert the values. I don't know if i am doing anything wrong, below is my php code.
<?php
include("connection.php");
$data = file_get_contents('php://input');
$json_data = json_decode($data);
foreach($json_data as $key => $val) {
$column_name = $key ;
$c_column_name = preg_replace('/[^a-zA-Z]+/', '', $column_name);
$column_value = $val ;
$table_name = "test2";
$email = "ht#t.com";
$result = mysqli_query($conn,"SHOW COLUMNS FROM $table_name LIKE '$c_column_name'");
$exists = (mysqli_num_rows($result))?TRUE:FALSE;
if($exists) {
$query1 = "INSERT INTO $table_name($c_column_name)VALUES('$column_value') ";
$data0=mysqli_query($conn,$query);
if($data0)
{
echo json_encode(array("success"=>"true - insertion","message"=>"Column existed, Successfully data sent."));
}
else{
echo json_encode(array("success"=>"false - insertion","message"=>"Column existed, data not inserted."));
}
}
else{
$query2="ALTER TABLE $table_name ADD COLUMN `$c_column_name` varchar(50) NOT NULL";
$data1=mysqli_query($conn,$query2);
if($data1){
$query3="INSERT INTO $table_name($c_column_name)VALUES('$column_value')";
$data2=mysqli_query($conn,$query3);
if($data2)
{
echo json_encode(array("success"=>"true - insertion","message"=>"Successfully data sent."));
}
else{
echo json_encode(array("success"=>"false - insertion","message"=>"Column created but data not inserted."));
}
}
else
{
echo json_encode(array("success"=>"false - column creation","message"=>"Failed to create column.'$column_name', '$table_name', '$conn'"));
}
}
}
?>
Here is the Json Object through postman.
{"Shape":"rewq","Trans.No.":"yuuiop","Color":"qwert"}
Please help me with this, any help or suggestions are highly appreciated.
The second column name is Trans.No. which contains a dot, this is why it fails, probably you have an error as a result which prevents further columns from being created.
I think it would be much better to have a table with this structure:
attributes(id, key, value)
and whenever a key-value pair is received, you just insert/update it, depending on the logic you need to be executed. Your current model will create a separate row for each attribute, which is probably not what you want to achieve.
EDIT
Based on the information received in the comment section I reached the following conclusion:
You could create the missing columns first and then generate the insert statement with all the columns, having a single insert.
But it would be better to not create a separate column for each value, as the number of columns could quickly get out of hand. Instead you could have a table:
myentity(id, name)
for storing the entities represented by the JSON and
attributes(id, myentity_id, key, value)
for storing its attributes. This would be a neat schema with all the dinamicity you could want.
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.
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);