sql - 更新而不覆盖现有信息

时间:2009-04-16 03:32:51

标签: php javascript sql mysql

我有以下条件代码,如果不存在具有相应用户名的记录,则会插入新记录,如果记录确实存在,则更新记录。这很好。

但是,目前,如果我插入一条新记录,并且只插入名字和姓氏,并且可能会说明电话信息留空的地址详情,这很好。如果我希望仅使用电话记录更新记录,则名称和地址信息将被替换为任何内容。

我想知道的是,是否可能有一种简单的方法来填充我的php html表单以更新信息,我将更新该字段的内容?我正在使用

 <input type="text" name="uniquename" />

获取用户输入,然后将其传递给javascript函数,然后将其传递回下面的php代码。如果这是不可能的,有没有一种简单的方法来处理一些sql / php魔法,只更新一个对应于非空的userinput的字段?

$usernameQuery = "select username from USERS where username = '" . $con->escape_string($username) . "'"; 

$xblah = $con->query($usernameQuery);
  while ($row = mysqli_fetch_assoc($xblah))
  {
    $checkUsername = $row['username'];
   }

if ($checkUsername == null) {

$userQuery = "INSERT INTO USERS VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
if ($userInfo = $con->prepare($userQuery)) {
    $userInfo->bind_param("ssssssssssssssssssss", $username, $firstname, $lastname, $flaggedauctions, $lastauction, $street1, $city1, $postcode1, $street2, $city2, $postcode2, $phone, $mobilephone, $fax, $email, $website, $bank, $banknumber, $accountnumber, $comments);
    $userInfo->execute();
    $userInfo->close();
    echo "true";
} else {
echo "false";
}
print_r($con->error);
}

else if ($checkUsername == $username) {

$userQuery = "UPDATE USERS SET firstname = ?, lastname = ?, flaggedauctions = ?, lastauction = ?, street1 = ?, city1 = ?, postcode1 = ?, street2 = ?, city2 = ?, postcode2 = ?, phone = ?, mobilephone = ?, fax = ?, email = ?, website = ?, bank = ?, banknumber = ?, accoutnumber = ? WHERE username = ?";
if ($userInfo = $con->prepare($userQuery)) {
    $userInfo->bind_param("sssssssssssssssssss", $firstname, $lastname, $flaggedauctions, $lastauction, $street1, $city1, $postcode1, $street2, $city2, $postcode2, $phone, $mobilephone, $fax, $email, $website, $bank, $banknumber, $accountnumber, $username);
    $userInfo->execute();
    $userInfo->close();
    echo "true";
} else {
echo "false";
}
print_r($con->error);
}

2 个答案:

答案 0 :(得分:1)

您只需要动态构建更新语句并绑定参数。 e.g。

$userQuery = "UPDATE ";

if (!empty($firstname)) {
  $userQuery += "firstname = ?,";
}

...    

if (!empty($firstname)) {
  $bindArgs[] = $firstname;
}
...

因此您的查询不会更新不应更改的列。

答案 1 :(得分:0)

更一般地说,请注意:

  • 明智的做法是在INSERT ... VALUES中指定你的列名,否则如果有人添加了一个列你会感到烦恼,如果有人重新排序这些列,你会感到困惑。

  • 您的选择和更新之间存在竞争条件......另一个进程可能会在您仍在思考时插入/删除一行,导致插入/更新失败请考虑:

    • INSERT ... ON DUPLICATE KEY UPDATE ...
    • 取代......