2

下面的代码是我如何从数据库中删除数据。用户选择他想要删除的标题,然后查询应该删除这些行。不幸的是,这行不通。

我已通过在 PhpMyAdmin 和 MySQL Workbench 中使用它来确保 DELETE 查询有效,但由于某种原因,我正在编码的 PHP 代码不允许删除工作。

<?php
    session_start();
    require ("../login.php");

    if (!isset($_SESSION['user'])) 
        header('Location: ../index.php');

    include ("header.php");
    include ("subnav.php");
?>

    <h2>Current Subscriptions</h2>

    <?php

    $user_id = $_SESSION['user'];

    if (isset($_POST['submit'])) {
        foreach($_POST["titles"] as $title) {
            $stmt = $db->prepare("DELETE FROM subscriptions WHERE user=:user AND title=:title)");
            $stmt->bindValue(':user', $user_id, PDO::PARAM_INT);
            $stmt->bindValue(':title', $title, PDO::PARAM_INT);
            $stmt->execute();
        }
        echo '<p>Thank you! Your changes have been made!</p>';
    }
    else {
        $stmt = $db->prepare
            ("SELECT t.id, t.publisher, t.title
            FROM titles t
                JOIN subscriptions s
                    ON t.id = s.title
            WHERE s.user=:user
            ORDER BY t.id");

        $stmt->bindValue(':user', $user_id, PDO::PARAM_STR);
        $stmt->execute();
        $rows = $stmt->fetchAll();
        $num_rows = count($rows);
        if ($num_rows == 0)
            echo 'You are not currently subscribed to any titles.';
        else {
            ?>
            <form action="" method="post">
            <?php   
            foreach($rows as $row) 
                echo '<input type="checkbox" name="titles[]" value="' . $row['id'] . '">' . $row['publisher'] . ' - ' . $row['title'] . '<br>';
            ?>
            <input type="submit" value="Update" name ="submit" id="submit">
                </form>
        <?php
        }
    }
    ?>

<?php   
    include ("footer.php");
?>
4

2 回答 2

3

我确实在您的 SQL 中看到了额外)内容,请尝试将其删除。

 ("DELETE FROM subscriptions WHERE user=:user AND title=:title)");
于 2013-04-10T22:44:20.117 回答
0

很难用你的代码来判断,但试着用你的 foreach 包装

try {
    foreach(...) {
        ...
    }
} catch (PDOException $ex) {
    $ex->getMessage();
}

这应该清楚地告诉你发生了什么。

于 2013-04-10T22:47:12.100 回答