Update Information first:
The cause for question is found. For Solution/Reason see end of this Posting ...
Here is some PHP code to update a data row in a sqlite DB using PDO:
$db = new PDO("sqlite:$db_name");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$update_data = array(
'animal' => 'cow',
'name' => 'Mary',
'age' => '4',
);
$stmt = $db->prepare( "UPDATE $db_table SET animal = :animal, name = :name, age = :age WHERE id = 48 " );
$stmt->execute($update_data);
echo $stmt->rowCount();
The (to me) strange behaviour is, that the page in the browser loads the page twice when this code is excuted.
NOTE: This happens only if the datas in the DB changed. If the update data are identical with DB data (so there is no change in the DB) the page only loads one time.
The Effect is the same:
when only this the code is on a plain PHP page (= initalize a new page load -> the page loads correct -> the DB action happens -> page automatic refreshs to load second time ?why?)
or if I initalize the code by a form request (= submit form -> action leads to the same page -> page loads correct -> afer processing POST data the code with this DB action is executed -> page automatic whants reload second time ?why?)
This effect does not exist when I run the same code on a MySql DB (tested on a Maria DB):
$db = new PDO("mysql:mysql:host=localhost;dbname=tst_animals", 'admin', 'admin' );
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$update_data = array(
'animal' => 'cow',
'name' => 'Mary',
'age' => '4',
);
$stmt = $db->prepare( "UPDATE $db_table SET animal = :animal, name = :name, age = :age WHERE id = 5 " );
$stmt->execute($update_data);
echo $stmt->rowCount();
This code is executed after the page has loaded without a automatic page refresh.
Can anyone explain the strange behaviour to me:
What in this code is the reason for the automatic page reload?
How can I avoid the automatic page reload (the Idea is: the DB action executes and nothing on the page itself changes)?
Thxs for all answers.
PS:
Please notice that this has nothing to do with try{...}catch(){...}. Using the code with try/catch shows same effect. I just reduced the code for testing and simplifying the issue here and tested it with/without try/catch as well.
The tested behaviour is the same if the code with the DB action is executed before (or even after) something has written to the page.
UPDATE AND SOLUTION
As in the comments was a remark that the code does not work here the working example for 'PDO sqlite', - I only added the variable settings, sorry for the little abstraction:
<?php
$db_name = "D:/xampp/htdocs/devClassForm/system/sqlite/db_animals.sqlite";
$db_table = "animals";
$db = new PDO("sqlite:$db_name");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$update_data = array(
'animal' => 'cow',
'name' => 'Mary',
'age' => '4',
);
$stmt = $db->prepare( "UPDATE $db_table SET animal = :animal, name = :name, age = :age WHERE id = 48 " );
$stmt->execute($update_data);
$stmt->rowCount();
DB table settings are:
[id, integer, autoincrement, primary key]
[animal, text]
[name, age]
[age,integer]
When testing please fill database and adapt id number in statement to your settings.
The plain code indeed works proper as it is. I copied it direct one to one from testing file , - but concerning to the insistings comments I checked the code once more and found the solution for the very strange and irritationg behaviour:
When I tested I used VS Code with Live Server Extension. This Setup in Firefox (not testet with Chrome...) indeed causes the auto refresh of the page (checked in the Server logs).
Deactivating this extension the code works as well, updates db data and the page only loads once.
Thxs for the help :-)
(I suggest to let this posting stay here and not to delete it even it is not really a coding issue. Maybe this information about the testing setup helps somone else some time to save time.)
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'm having a problem with the query it works fine in SQL server but when I trying to return the row in PHP it comes back without any results. See the code below the issue is with this field SO_SalesOrderHistoryDetail.ItemCodeDesc this field is exactly what it sounds like it's an item description and on this particular record it has this data in it. ACC, Smart-Trek™ Deluxe Stereo
I have confirmed this is the issue ™ for some reason this field will not display in PHP. I could edit the data although I would like to reserved that option for a last ditch effort. I'm not sure why this particular data is stopping all information from being returned. I don't get a PHP error. Any help would be most welcome much appreciated.
$tsql = "
SELECT
SO_SalesOrderHistoryHeader.CustomerNo,
SO_SalesOrderHistoryHeader.CustomerPONo,
SO_SalesOrderHistoryDetail.SalesOrderNo,
SO_SalesOrderHistoryDetail.CancelledLine,
SO_SalesOrderHistoryDetail.ItemCode,
SO_SalesOrderHistoryDetail.ItemCodeDesc,
SO_SalesOrderHistoryDetail.QuantityBackordered,
SO_SalesOrderHistoryDetail.QuantityOrderedRevised,
SO_SalesOrderHistoryDetail.PurchaseOrderNo,
SO_SalesOrderHistoryDetail.QuantityShipped,
SO_SalesOrderHistoryHeader.OrderStatus,
SO_SalesOrderHistoryHeader.OrderDate,
SO_SalesOrderHistoryHeader.CustomerPONo
FROM SO_SalesOrderHistoryDetail
INNER JOIN SO_SalesOrderHistoryHeader ON
SO_SalesOrderHistoryDetail.SalesOrderNo = SO_SalesOrderHistoryHeader.SalesOrderNo
WHERE
(SO_SalesOrderHistoryHeader.CustomerNo = 'XXXXXXX') AND
(SO_SalesOrderHistoryHeader.OrderStatus <> 'X') AND
(SO_SalesOrderHistoryDetail.CancelledLine = 'N') AND
(SO_SalesOrderHistoryHeader.CustomerPONo = 'XXXXXXX')
";
$getResults= sqlsrv_query($connms, $tsql);
$row = sqlsrv_fetch_array($getResults);
I found the answer I thought I'd pass it along to help others. It can be found at the URL below.
Add this for your connection configuration array: "CharacterSet" =>"UTF-8".
For example:
$connectionInfo = array( "Database"=>"DBName", "CharacterSet" =>"UTF-8" );
https://learn.microsoft.com/en-us/archive/blogs/brian_swan/sql-server-driver-for-php-connection-options-characterset
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've been having problems trying to update a value based off a code that is received on the page.
For example:
http://example.com/register.php?code=fa82f82712d1 (not the actual code, it's always a 32-char code actually).
I start a transaction, and do an update in the following way:
$stmt = $stmt->prepare("UPDATE USER SET GOT_CODE = 1 WHERE CODE = :code");
Then do a $stmt->execute(array(':code' => $code)); from the code gotten before.
But it never updates anything, I'm running a rowCount() (gives me '0') and closing the transaction but can't seem to get it updated.
The column type is CHAR(32) which should match with the length of the code received.
Is it possible that it's causing confusions because of the data type?
Maybe bind the parameter before like:
$stmt2 = $stmt->prepare("UPDATE USER SET GOT_CODE = 1 WHERE CODE = :code");
$stmt2->bindParam(":code", $code, PDO::PARAM_STR);
if ($stmt2->execute()){
$stmt->commit();
} else {
$stmt->rollBack();
}
EDIT: after comment of other people. The basic is to not use
$stmt = $stmt->prepare("UPDATE USER SET GOT_CODE = 1 WHERE CODE = :code");
but to give different var name like
$stmt2 = $stmt->prepare("UPDATE USER SET GOT_CODE = 1 WHERE CODE = :code");
because otherwise the system will overwrite $stmt and not work anymore
I can't figure out why this code is inserting the same row twice. I've literally stripped it back to the following code:
<?php
$query = "INSERT INTO `cs_social_alerts` (email) VALUES ('test#test.com')";
mysql_query($query);
?>
The MySQL table it's being inserted into has 10 columns in it, but even with all of them mentioned in the query, it still inserts 'test#test.com' on two rows, with separate primary keys.
I've created a new WordPress page to run this on as all other pages seem to be functioning fine without the duplication.
I've done some Googling which hasn't found much of any help - Is there any way I can check where the second query is coming from? I've starred at the above code for about an hour now and cannot see any issues with it.
So here's the result from the debug traceback, the code that's being run is literally the 2 lines above - I've blanked the domain for security. Can anyone see any interference?
#0 eval() called at [/var/sites/c/****.com/public_html/wp-content/plugins/wp-exec-php/wp-exec-php.php:652]
#1 WP_exec_PHP->exec(
$myQuery = "INSERT INTO `cs_social_alerts` (email) VALUES ('test#test.com')";
mysql_query($myQuery);
debug_print_backtrace()
?>
) called at [/var/sites/c/****.com/public_html/wp-content/plugins/wp-exec-php/wp-exec-php.php:692]
#2 WP_exec_PHP->_exec_post(
$myQuery = "INSERT INTO `cs_social_alerts` (email) VALUES ('test#test.com')";
mysql_query($myQuery);
debug_print_backtrace()
?>
)
#3 call_user_func_array(Array ([0] => WP_exec_PHP Object ([] => Array (),[] => /var/sites/c/*****.com/public_html/wp-content/plugins/wp-exec-php/wp-exec-php.php),[1] => _exec_post), Array ([0] =>
$myQuery = "INSERT INTO `cs_social_alerts` (email) VALUES ('test#test.com')";
mysql_query($myQuery);
debug_print_backtrace()
?>
)) called at [/var/sites/c/*****.com/public_html/wp-includes/plugin.php:192]
#4 apply_filters(the_content,
$myQuery = "INSERT INTO `cs_social_alerts` (email) VALUES ('test#test.com')";
mysql_query($myQuery);
debug_print_backtrace()
?>
Use the PHP function debug_print_backtrace() to find out where your code is being called from.
Try a PHP Data Object(PDO). Using the mysql_* functions are obsolete.
These variable initializations should be defined in an ini file that you use php_parse_ini() to get the data from.
<?php
$host = "host=localhost";
$name = ";dbname=name_of_db";
$user = "user";
$pass = "pass";
$conn = new PDO("mysqli:".$host.$name,$user,$pass);
$stmt = $conn->prepare("INSERT INTO `cs_social_alerts` (email) VALUES (:email)");
$stmt->bindParam(':email', $email);
$stmt->execute();
Also, if you want to know if this code is getting run more than once. Try setting a $_SESSION variable. I.E. $_SESSION['count'] = 0; Then right before execute() put $_SESSION['count']++; Finally, dump the value of $_SESSION at the end of your code to determine what the value is.
var_dump($_SESSION);die();
I had the same problem, and it was chrome fault!
I clear the sessions, cookies, cache, all data application and it works.
Have you tried another browser? I had plenty of bad experiences because some extensions that I had in my browser were requesting the page one more time.
Even if that's not your problem, I think you should check for external factors, as this code cannot insert two rows. Unless, of course, it's being called twice.