更新记录然后删除

时间:2016-12-01 04:34:16

标签: php mysql

我正在尝试更新一条记录,然后一次删除另一条记录,但它只允许我做一个或另一个;

$update = "UPDATE user SET felcredits = '$value' WHERE username = '$user'";
$update2 = "DELETE FROM playeritems WHERE id = '$realid'";

我如何做到这两点? 我尝试了以下内容;

$update = "UPDATE user SET felcredits = '$value' WHERE username = '$user'";
$update = "DELETE FROM playeritems WHERE id = '$realid'";

__

$update = "UPDATE user SET felcredits = '$value' WHERE username = '$user' DELETE FROM playeritems WHERE id = '$realid'";

__

完整代码:

if ($_SERVER['REQUEST_METHOD'] = $_POST AND isset($_POST['sell'])) {
$sql = "SELECT felcredits FROM user WHERE username = '$user'";
$result = $db_conn->query($sql);
if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        $felcredits = $row['felcredits'];
    }
}
$value = $felcredits + $value;
$update = "UPDATE user SET felcredits = '$value' WHERE username = '$user'";
$update2 = "DELETE FROM playeritems WHERE id = '$realid'";
if ($db_conn->query($update) === TRUE) {
    echo "<br />Details Updated";
} else {
    echo "Error: " . $insert . "<br>" . $db_conn->error;
}

}

2 个答案:

答案 0 :(得分:4)

问题在于:

$update = "UPDATE user SET felcredits = '$value' WHERE username = '$user'";
$update = "DELETE FROM playeritems WHERE id = '$realid'";

您的第二个SQL查询将覆盖第一个,因此请单独进行查询:

$update = "UPDATE user SET felcredits = '$value' WHERE username = '$user'";
mysqli_query($conn, $update);

$delete = "DELETE FROM playeritems WHERE id = '$realid'";
mysqli_query($conn, $delete);

其中$ conn是连接句柄

答案 1 :(得分:0)

您尝试更改完整代码,例如

在您的执行代码

if ($_SERVER['REQUEST_METHOD'] = $_POST AND isset($_POST['sell'])) {
 $sql = "SELECT felcredits FROM user WHERE username = '$user'";
$result = $db_conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
    $felcredits = $row['felcredits'];
}
}       
$value = $felcredits + $value;
$update = "UPDATE user SET felcredits = '$value' WHERE username = '$user'";
$update2 = "DELETE FROM playeritems WHERE id = '$realid'";
if (($db_conn->query($update) === TRUE) && ($db_conn->query($update2) ===     TRUE)) {
echo "<br />Details Updated";
} else {
echo "Error: " . $insert . "<br>" . $db_conn->error;
}
}