2

I know how to update the rows in my database, I know how to transfer data from one page to another, but what I don't know is a good way to update the database of several different rows as long as the variable aren't empty.

What I am working on is a user page with settings to change real name, username, password and similar, but I have no clue of how to just update the once I have changed. If I leave for example "Username" empty and press "Change Settings", then it empties the row of username. How do I make it ignore the empty variables?

Henrik Gustafsson
  • 51,180
  • 9
  • 47
  • 60
Richard Atterfalk
  • 462
  • 1
  • 10
  • 23

7 Answers7

1

You most likely want to use prepared statements to accomplish this. Both to make the code prettier and more robust, and to avoid SQL injections (alternative).

Now, since you want to update different columns based on some condition, you have a few alternatives on how to continue.

One would be to use several update statements (one for each column you wish to update) and bundle them inside a transaction. Bundling the statements inside a transaction will ensure atomicity and will also help mitigate the performance impact of using several SQL statements in place of one (something that won't likely matter unless you have many concurrent users).

It would probably look something like this (using the mysqli API):

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("dbhost", "dbuser", "dbpassword", "dbname");
$mysqli->autocommit(FALSE);

if ($userName) {
    $stmt = $mysqli->prepare("UPDATE TABLE users SET username=? WHERE uid=?");
    $stmt->bind_param("si", $userName, $uid);
    $stmt->execute();
}

if ($password) {
    $stmt = $mysqli->prepare("UPDATE TABLE users SET password=? WHERE uid=?");
    $stmt->bind_param("si", $password, $uid);
    $stmt->execute();
}

if ($firstName) {
    $stmt = $mysqli->prepare("UPDATE TABLE users SET firstname=? WHERE uid=?");
    $stmt->bind_param("si", $firstName, $uid);
    $stmt->execute();
}

if ($lastName) {
    $stmt = $mysqli->prepare("UPDATE TABLE users SET lastname=? WHERE uid=?");
    $stmt->bind_param("si", $lastName, $uid);
    $stmt->execute();
}

$mysqli->commit();
$mysqli->close();

For brevity I've left out the error handling; you'd need to check for connection failures and problems preparing the statements as well as the execution of them. If anything fails after the first execute() line you need to call $mysqli->rollback() to make sure no changes are performed.

You would also be well advised to refactor the code so it doesn't repeat itself quite so much, something like this perhaps:

function updateColumn($mysqli, $query, $uid, $value) {
    if ($value) {
        $stmt = $mysqli->prepare($query);
        $stmt->bind_param("si", $value, $uid);
        $stmt->execute();
    }
}

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("dbhost", "dbuser", "dbpassword", "dbname");
$mysqli->autocommit(FALSE);

updateColumn($mysqli, "UPDATE TABLE users SET username=? WHERE uid=?", $uid, $userName);
updateColumn($mysqli, "UPDATE TABLE users SET password=? WHERE uid=?", $uid, $password);
updateColumn($mysqli, "UPDATE TABLE users SET firstname=? WHERE uid=?", $uid, $firstName);
updateColumn($mysqli, "UPDATE TABLE users SET lastname=? WHERE uid=?", $uid, $lastName);

$mysqli->commit();
$mysqli->close();

You could take it a few steps further and generate the query as well, that's rather safe since you are not depending on/using user input to generate the query. This would get hairy fairly quickly though.

The other ways would be the ones already mentioned here, or combining the dynamic generation of the query with prepared statements. You might also want to try to do the same with the PDO API.

Probably the best way in the long term would probably be to use a third-party ORM framework (see this related question for suggestions).

Dharman
  • 30,962
  • 25
  • 85
  • 135
Henrik Gustafsson
  • 51,180
  • 9
  • 47
  • 60
0

why not populate the fields of your form with the current values stored in the database?

eg.

<input type="text" name="name" value="<?php echo $(value currently in db);?>" />

So even if they arent changed you will still have the old value.

callum.bennett
  • 678
  • 3
  • 12
  • 28
0

You can do so:

  $values = array();
  foreach($user_data as $key => $value)
    if (isset($value) && trim($value) != '')
      $values[] = $key.' = "'.mysql_real_escape_string($value).'"';

  $sql = 'UPDATE users SET '.implode(', ', $values).' WHERE id = '.$id;

  mysql_query($sql);
?>
Hck
  • 9,087
  • 2
  • 30
  • 25
-1

Something like this maybe (untested) ... although you'll need to protect against sql injection. This is just a general idea.

if(isset($_POST['submit']))
{
    $query = "UPDATE tbl SET ";
    if(isset($_POST['firstname']) && $_POST['firstname'] != "") $query .= "firstname = ".$_POST['firstname'];
    //execute query
}
AllisonC
  • 2,973
  • 4
  • 29
  • 46
-1

If you use $_POST/$_GET in your query you can build it like that.

Example with $_POST:

<?php
$MoreSQL = '';
if (trim($_POST['username'] != '')) {
    $MoreSQL .= 'username="'.trim($_POST['username']).'"';
}

if (trim($_POST['password'] != '')) {
    if ($MoreSQL)
        $MoreSQL .= ', '; // add comma if $MoreSQL is not empty
    $MoreSQL .= 'password="'.trim($_POST['password']).'"';
}

if (trim($_POST['firstname'] != '')) {
    if ($MoreSQL)
        $MoreSQL .= ', '; // add comma if $MoreSQL is not empty
    $MoreSQL .= 'firstname="'.trim($_POST['firstname']).'"';
}

if (trim($_POST['lastname'] != '')) {
    if ($MoreSQL)
        $MoreSQL .= ', '; // add comma if $MoreSQL is not empty
    $MoreSQL .= 'lastname="'.trim($_POST['lastname']).'"';
}

if (!$MoreSQL) { // if everything is empty, no need to fire mysql_query
    echo 'nothing to update';
} else { // otherwise, update the record
    mysql_query('UPDATE mytable SET '.$MoreSQL.' WHERE membersID='.($_POST['membersID'] + 0).'');
}
?>

Hope it make sense to you.

RRStoyanov
  • 1,162
  • 1
  • 13
  • 23
  • Where you have used comma (,) – Vineet1982 May 26 '11 at 13:49
  • Do you look carefully? What about the if ($MoreSQL) $MoreSQL .= ', '; // add comma if $MoreSQL is not empty. You can't see that 3 times, huh.... – RRStoyanov May 26 '11 at 13:50
  • Makes quite good sense, yes. I think it will work and shall add it to the code and test it as soon as I'm back in that area. Thank you. – Richard Atterfalk May 31 '11 at 20:19
  • -1 This is very vulnerable to SQL injection, not recommended! – Lekensteyn Mar 21 '13 at 11:16
  • You didn't have what to do so answer an question old 2 years ago and not to mention nobody talks about security here. YES, security is very important, but should I add 10 pages of explaining people how to do it? I couldn't take that, sorry... – RRStoyanov Mar 21 '13 at 22:37
-1

Still can't get it to work. I have tried RRStoyanov suggestion since it seemed to be the most reasonable and I ended up with this:

if (trim($_POST['style'] != '')) {
    if ($MoreSQL)
        $MoreSQL .= ', '; // add comma if $MoreSQL is not empty
    $MoreSQL .= 'css="'.trim($_POST['style']).'"';
}

if (!$MoreSQL) { // if everything is empty, no need to fire mysql_query
    echo 'nothing to update';
} else { // otherwise, update the record
    mysql_query("UPDATE ´database SET '.$MoreSQL.' WHERE usernamename='.$u_name.'");
}

Before that I used:

mysql_query("UPDATE $tbl_name SET css='$css' WHERE username='$u_name'");

This worked rather well for me, but couldn't update correctly with several options since none of them should be empty. If any is empty then the users might erase their username or password.

Richard Atterfalk
  • 462
  • 1
  • 10
  • 23
-2

Why do want to have the value empty. You can describe during form. Such as:

<input type="text" name="firstname" values=<?php echo $firstname;?>

and on submit check as

$query = "Update table SET "
if(isset($_POST['firstname']) && strlen($_POST['firstname'])>0){
    $query.= "firstname = ".$_POST['variable'];
}
Vineet1982
  • 7,730
  • 4
  • 32
  • 67
  • you will need to add a check if more than two fields need to be updated. than it should add comma before the sql statement. – RRStoyanov May 26 '11 at 13:46
  • that is true, what I provide a simple example not a complete code – Vineet1982 May 26 '11 at 13:48
  • Maybe adding a message "this is just an example, not complete solution" will be good. If a beginner ask and try your code, he will just say not work. Nothing against you, just my opinion how we should approach to questions. Don't you agree? – RRStoyanov May 26 '11 at 13:52