WordPress.org

Forums

wpdb update won't update if the new data is the same as the old. (4 posts)

  1. mmx38
    Member
    Posted 8 months ago #

    Hello!

    I am using wpdb to query some tables outside wordpress.

    The problem is that if I try to give a WPDB->update query, it will run only when the new data are different than the old ones..

    For example
    I have a table MyNames with 4 columns:
    Id
    first_name
    last_name
    LastUpdated

    I have a record like this:

    3 | John | Doe | 2014-07-19 12:00:00

    If I run the query below, it works. It replaces the name and the "LastUpdated" field is automatically updated (I have set it to the database as timestamp with CURRENT_TIMESTAMP ).

    $wpdb->update(
    'MyNames',
    array(
    "first_name" => "Danny",
    "last_name" => "Texas"
    ),
    array( 'Id' => 3),
    array(
    '%s', // value1
    '%s' // value2
    ),
    array( '%d' )
    );

    If I run the same query but instead of Danny Texas I use John Doe then it will not work. You may think that "What you expect to change if the new data is the same?".. Hmm I would expect the LastUpdated to be changed.. to get the new timestamp.

    Can anyone explain why does this happen? Is there any way to trick it and send something like NOW() to the timestamp?

    Thanks!

  2. DionDesigns
    Member
    Posted 8 months ago #

    There is no way to "trick" the database. If you want the LastUpdated field to update every time, then you must set it yourself.

    FYI, it is much more efficient to set that column as INT(11) and storing a UNIX timestamp. The timestamp can be generated with the PHP time() fumction just prior to updating. When the timestamp is retrieved, it can be formatted with the PHP date() function.

  3. mmx38
    Member
    Posted 8 months ago #

    Thank you for your reply DionDesigns.

    I think that if I change the functionality to store the Unix timestamp it will do the trick. I 'll test it tonight!

    When I said to "trick it" I did not mean the database but the wpdb.

    Anyway, is this the normal functionality not to update the record if old and new data is the same?

  4. RossMitchell
    Member
    Posted 8 months ago #

    Another way to update a timestamp field to NOW() is to set it to null in the update.

Reply

You must log in to post.

About this Topic

Tags

No tags yet.