首页 > 解决方案 > 使用 SQL 的删除按钮无法正常工作

问题描述

我正在做一个唱片项目,但我遇到了一个问题,即“删除选择”按钮没有删除该行。到目前为止,我与数据库的连接正常,它正确地回显了信息,但实际上并没有从数据库中删除该行。我目前正在使用 MySQLi。

这是完整的代码:

<?php
include '../includes/connection.php';
//Include from admin folder
include './includes/login.php';
login();

// initialize flags
$OK = false;
$deleted = false;
$stmt = $conn->stmt_init();

if (isset($_GET['id']) && !$_POST) {
    // prepare SQL query
    $sql = 'SELECT id, album_name FROM album2img WHERE id = ?';
    if ($stmt->prepare($sql)) {
        // bind the query parameters
        $stmt->bind_param('i', $_GET['id']);
        // execute the query, and fetch the result
        $OK = $stmt->execute();
        // bind the result to variables
        $stmt->bind_result($id, $album_name);
        $stmt->fetch();
    }
}

if (isset($_POST['delete'])) {
    $sql = 'DELETE FROM album2img WHERE id = ?';
    if ($stmt->prepare($sql)) {
        $stmt->bind_param('i', $_POST['id']);
        $stmt->execute();
        // if there's an error affected_rows is -1
        if ($stmt->affected_rows > 0) {
            $deleted = true;
        } else {
            $error = 'There was a problem deleting the record.';
        }
    }
}

if ($deleted || isset($_POST['cancel']) || !isset($_GET['id']))  {
    header('Location: http://localhost/3rdquarterproject/admin/album_list.php');
    exit;
}

// if any SQL query fails, get the error message
if (isset($stmt) && !$OK && !$deleted) {
    $error .= $stmt->error;
}

?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Delete Album</title>
  </head>
  <body>
    <h1>Delete Album</h1>
    <?php
    if (isset($error) && !empty($error)) {
        echo "<p>Error: $error</p>";
    }
    if($id == 0) { ?>
        <p>Invalid request: record does not exist.</p>
    <?php } else { ?>
        <p>Please confirm that you want to delete the following item. This action cannot be undone.</p>
        <p><?php echo $id; echo ". "; echo $album_name; ?></p>
    <?php } ?>
    <form method="post" action="album_delete.php">
        <p>
            <?php if(isset($id) && $id > 0) { ?>
                <input type="submit" name="delete" value="Confirm Deletion">
            <?php } ?>
            <input name="cancel" type="submit" value="Cancel">
            <?php if(isset($id) && $id > 0) { ?>
                <input name="album_name" type="hidden" value="<?= $album_name; ?>">
            <?php } ?>
        </p>
    </form>
  </body>
</html>

我不确定我是否在删除部分正确使用了准备好的语句:

    if (isset($_POST['delete'])) {
    $sql = 'DELETE FROM album2img WHERE id = ?';
    if ($stmt->prepare($sql)) {
        $stmt->bind_param('i', $_POST['id']);
        $stmt->execute();
        // if there's an error affected_rows is -1
        if ($stmt->affected_rows > 0) {
            $deleted = true;
        } else {
            $error = 'There was a problem deleting the record.';
        }
    }
}

我还是很新,所以期待大家的回应!

标签: phpsqlmysqli

解决方案


推荐阅读