cwiggo
cwiggo

Reputation: 2609

Logging profile updates in PHP

I have a edit profile page in my social media website.

When users click submit on the form. I run an update query to obviously update the users field in the database.

How can I optimize this scenario to include the logging of which particular fields are updated?

So for e.g.

One scenario could be:

Chris updated his profile picture.

Another scenario would be:

Chris updated his profile, inc:

Can anyone offer a solution to this?

I feel there is no need for code as all it is, is an update query.

Thanks

Upvotes: 0

Views: 93

Answers (3)

Hampus Brynolf
Hampus Brynolf

Reputation: 1336

When writing out the form, save the current states in the $_SESSION-variable. The check the submitted forms and compare with the data in the $_SESSION-variable. Then only make an update on the forms that have changed.

if($_SESSION['name'] != $myform['name']) { $sql[] = "name = '{$myform['name']}'"; }
if($_SESSION['img'] != $myform['img']) { $sql[] = "img = '{$myform['img']}'"; }
$sqlstring = "UPDATE mytable SET " . implode(",",$sql);
// run the sql

EDIT: to implement logging:

// populate the variables (name, img) from the db/session with the highest revision number.
// ie SELECT * FROM mytable where userid = $userid ORDER BY revision DESC LIMIT 1
$revision = $_SESSION['revision'] + 1;
$sql = "INSERT INTO mytable SET img = '$img', name='$name', revision='$revision'"; 

Upvotes: 1

Vlad Preda
Vlad Preda

Reputation: 9920

You can use custom setters / getters to do this. Check the code below.

You can also add additional checks to make sure the values have changed, or use magic methods to make things more dynamic.

class MyObject
{
    protected $modifiedFields = array();
    public function setField($value) {
        if (!in_array('field', $this->modifiedFields)) {
            $this->modifiedFields[] = 'field';
        }
    }
}

If you have the modified fields, you can just run the update query to contain only these fields.

Upvotes: 0

Refilon
Refilon

Reputation: 3499

Did you put all that information in a $_SESSION or something? If so, you can unset the session and declare it again, with the new info.

Upvotes: 0

Related Questions