【问题标题】:Delete rows from table using checkboxes使用复选框从表中删除行
【发布时间】:2013-03-30 11:21:49
【问题描述】:

我正在尝试根据复选框从表中删除多行,但是我不太确定如何最好地执行此操作。目前,我有一个电影列表,我希望能够根据它们是否被选中来删除其中一部或多部。

// Update Watchlist
    if ($submit == 'Update Watchlist') { 
        require_once("db_connect.php");

        $watchlist_name = clean_string($_POST['watchlist-name']);
        $watchlist_description = clean_string($_POST['watchlist-description']);
        $watchlist_category = $_POST['watchlist-category'];

        $updateWatchlist_bad_message = '';

        if (!empty($watchlist_name)) {
            if ($watchlist_name = clean_string($watchlist_name)) {
                $update_watchlist_name_query = "UPDATE watchlists SET name = '$watchlist_name' WHERE watchlist_id = " . $watchlist_id;
                mysql_query($update_watchlist_name_query) or die("Insert failed. " . mysql_error() . "<br />" . $$update_watchlist_name_query);
            }
        } 
        if (!empty($watchlist_description)) {
            if ($watchlist_description = clean_string($watchlist_description)) {
                $update_watchlist_description_query = "UPDATE watchlists SET description = '$watchlist_description' WHERE watchlist_id = " . $watchlist_id;
                mysql_query($update_watchlist_description_query) or die("Insert failed. " . mysql_error() . "<br />" . $$update_watchlist_description_query);
            }
        }
        if ($watchlist_category != "") {
            $update_watchlist_category_query = "UPDATE watchlists SET category = '$watchlist_category' WHERE watchlist_id = " . $watchlist_id;
            mysql_query($update_watchlist_category_query) or die("Insert failed. " . mysql_error() . "<br />" . $$update_watchlist_category_query);
        }
        if(isset($_POST['film-name'])) {
            $checkbox = $_POST['film-name'];
            $count = count($checkbox);

            for($i = 0; $i < $count; $i++) {
                $id = (int) $checkbox[$i]; // Parse your value to integer

                if ($id > 0) { // and check if it's bigger then 0
                    mysql_query("DELETE FROM watchlist_films WHERE film_id = $rt_id");
                }
            }
        } else {
            $updateWatchlist_bad_message = '<div class="alert alert-error">Sorry, but we can\'t do that at the minute. Please try again later.</div>';
        }
        require_once("db_close.php");?>
        <script type="text/javascript">
            window.location = "watchlist.php?id=<?php echo $watchlist_id; ?>"
        </script><?php
    }

适当的字符串是电影名称,我已尝试使用此解决方案 - PHP to delete SQL row with multiple checkboxes - 但是它不起作用,因为电影没有从包含的监视列表中删除。

基本上,我的查询背后的逻辑如下:

  • 检查是否勾选了一个复选框
  • 如果勾选了一个复选框,请检查是否也勾选了其他复选框
  • 从关注列表中删除所有已勾选的电影

我不确定上述是否是最简单的方法,例如,只需检查是否有任何复选框被一次性勾选,而不是先检查是否有任何复选框被选中,可能更简单、更清晰在检查其他人是否也做过之前打勾。

更新

只是想我会用更多信息澄清一下——我的实际 foreach 显示了关注列表中的所有电影,如下(对格式表示歉意):

foreach ($films as $key => $film_item) {
    include ("watchlist-film-controller.php");?>    
    <label class="checkbox input-block-level">
      <p class="pull-right"><?php echo $title; ?></p>
      <input type="checkbox" class="input-block-level" name="film-name[]" 
             value="<?php echo $title; ?>">
    </label><?php
}

更新 2

为了回答这篇文章中的两位(非常感谢!)cmets,这里有更多关于现在正在发生的事情的信息。我已经尝试了这两种解决方案,但都没有奏效。就目前而言,我已经实现了 didierc 给出的解决方案,我的代码目前看起来像这样:

<?php
/*
        ini_set('display_errors', 1);
    error_reporting(E_ALL);
*/
    $rt_id = $film_item['film_id'];
    $watchlist_id = $_GET['id'];

    include_once('/api/RottenTomatoes.php');
    $rottenTomatoes = new RottenTomatoes('2b2cqfxyazbbmj55bq4uhebs', 10, 'us');

    /* echo "<pre>"; */
    try {
        $result = $rottenTomatoes->getMovieInfo($rt_id);
        //print_r($result);
    } catch (Exception $e) {
        //print_r($e);
    }
    /* echo "</pre>"; */

    $title = $result['title'];
    $year = $result['year'];
    $critics_consensus = $result['critics_consensus'];
    $poster_thumb = $result['posters']['thumbnail'];

    // Update Watchlist
    if ($submit == 'Update Watchlist') { 
        require_once("db_connect.php");

        $watchlist_name = clean_string($_POST['watchlist-name']);
        $watchlist_description = clean_string($_POST['watchlist-description']);
        $watchlist_category = $_POST['watchlist-category'];

        $updateWatchlist_bad_message = '';

        if (!empty($watchlist_name)) {
            if ($watchlist_name = clean_string($watchlist_name)) {
                $update_watchlist_name_query = "UPDATE watchlists SET name = '$watchlist_name' WHERE watchlist_id = " . $watchlist_id;
                mysql_query($update_watchlist_name_query) or die("Insert failed. " . mysql_error() . "<br />" . $$update_watchlist_name_query);
            }
        } 
        if (!empty($watchlist_description)) {
            if ($watchlist_description = clean_string($watchlist_description)) {
                $update_watchlist_description_query = "UPDATE watchlists SET description = '$watchlist_description' WHERE watchlist_id = " . $watchlist_id;
                mysql_query($update_watchlist_description_query) or die("Insert failed. " . mysql_error() . "<br />" . $$update_watchlist_description_query);
            }
        }
        if ($watchlist_category != "") {
            $update_watchlist_category_query = "UPDATE watchlists SET category = '$watchlist_category' WHERE watchlist_id = " . $watchlist_id;
            mysql_query($update_watchlist_category_query) or die("Insert failed. " . mysql_error() . "<br />" . $$update_watchlist_category_query);
        }
        if(isset($_POST['film-name'])) {
            $films = array_map('intval', $_POST['film-name']); // make sure that every film id is an integer
            mysql_query("DELETE FROM watchlist_films WHERE film_id IN (" . implode(',', $films) . ") AND watchlist_id = " . $watchlist_id);
        } else {
            $updateWatchlist_bad_message = '<div class="alert alert-error">Sorry, but we can\'t do that at the minute. Please try again later.</div>';
        }
        require_once("db_close.php");?>
        <script type="text/javascript">
            window.location = "watchlist.php?id=<?php echo $watchlist_id; ?>"
        </script><?php
    }

$rt_id 是每部电影的唯一 ID,并且正在传递给表单,因此查询知道在这种情况下应该删除哪些电影或哪些电影。电影的名称仅用于使实际的删除表单更易于阅读,而不是打印出 ID 号列表,因为用户无法知道哪个 ID 与哪个电影匹配。在尝试了给出的两种解决方案后,似乎都没有工作,但是没有返回任何错误 - 表单提交,但所选电影不会从监视列表中删除。

更新 3

针对 didierc 的评论,以下是正在发生的事情的完整细分:

  • 监视列表分为两个表 - watchlistswatchlist_filmswatchlists 包含简单信息,例如监视列表 ID、名称和描述,以及创建它的用户的用户 ID。 watchlist_films 仅包含监视列表 ID 和监视列表包含的电影 ID ($rt_id)。监视列表占用 watchlists 表中的单行和 watchlist_films 表中的多行(因为一个监视列表可以包含多部电影)。
  • 电影信息正在从烂番茄和 TMDb API 中恢复,这就是电影 ID ($rt_id) 的来源 - 每部电影都有一个完全唯一的 $rt_id

关注列表的完整“处理代码”在 Update 2 中,但 HTML 呈现如下:

<?php 
    include("checklog.php"); 
    require_once("watchlist-controller.php");
?>
<!DOCTYPE html>

    <head>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <link rel="shortcut icon" href="img/fav.ico">
        <link rel="apple-touch-icon" href="img/apple-touch-icon.png">
        <title>Screening - Your ticket to your movies - <?php echo $watchlist_name; ?></title>
        <meta name="description" content="Screening is a brand new take on the traditional movie database, fusing social networking and multimedia to provide a clear, concise experience allowing you to share your favourite movies, and discover new classics.">
        <meta name="keywords" content="Movies, Films, Screening, Discover, Watch, Share, experience, database, movie database, film database, share film, share films, discover film, discover films, share movie, share movies, discover movie, discover movies">

        <!-- Bootstrap -->
        <link href="css/bootstrap.css" rel="stylesheet" media="screen">
        <link href="css/bootstrap-responsive.css" rel="stylesheet">
        <link href="css/custom-bootstrap.css" rel="stylesheet">
        <link rel="stylesheet" href="fonts.css" type="text/css" />
        <link rel="stylesheet/less" type="text/css" href="css/stylesheet.less" />
        <script src="js/less-1.3.3.min.js" type="text/javascript"></script>
        <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
        <script src="js/bootstrap.min.js"></script>

        <!-- Start Google Analytics -->
        <script type="text/javascript">

          var _gaq = _gaq || [];
          _gaq.push(['_setAccount', 'UA-36943512-1']);
          _gaq.push(['_trackPageview']);

          (function() {
            var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
            ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
            var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
          })();

        </script>
        <!-- End Google Analytics -->

        <!-- Start Google Analytics -->
        <script type="text/javascript">

          var _gaq = _gaq || [];
          _gaq.push(['_setAccount', 'UA-36943512-1']);
          _gaq.push(['_trackPageview']);

          (function() {
            var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
            ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
            var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
          })();

        </script>
        <!-- End Google Analytics -->

    </head>

    <body>

        <div class="container"><?php 
            require_once ("header.php");?>

            <div class="well main-content">

                <p class="page-title"><?php echo $watchlist_name; ?></p>

                <div class="row-fluid">

                    <section class="span3 sidebar pull-left">

                        <p class="sidebar-text"><span class="bold">NAME: </span><?php echo $watchlist_name; ?></p>
                        <p class="sidebar-text"><span class="bold">CATEGORY: </span><?php echo $watchlist_category; ?></p>
                        <div class="alert alert-info"><?php echo $watchlist_description; ?></div>

                        <a href="#watchlistUpdate" class="btn btn-primary btn-block" data-toggle="modal" title="Update Watchlist">Update Watchlist</a>
                        <a href="#watchlistDelete" class="btn btn-danger btn-block" data-toggle="modal" title="Delete Watchlist">Delete Watchlist</a>
                        <a href="profile.php" class="btn btn-block" title="Logout">Your Profile</a>


                    </section>

                    <section class="span9 watchlist-holder">

                        <!-- Loading bar -->
                        <!--
<div class="progress progress-striped active">
                            <div class="bar" style="width: 100%;"></div>
                        </div>
-->

                        <ul class="unstyled"><?php

                            foreach($films as $key => $film_item) {
                                include ("watchlist-film-controller.php");?>
                                <li class="well list-item clearfix">

                                    <div class="row-fluid">
                                        <a href="movie.php?id=<?php echo $rt_id; ?>" class="span1 pull-left" title="<?php echo $title; ?>"><img src="<?php echo $poster_thumb; ?>" alt="<?php echo $title; ?> poster" title="<?php echo $title; ?> poster" /></a>

                                        <div class="span11 movie-info">
                                            <p class="search-title"><a href="movie.php?id=<?php echo $film_item['film_id']; ?>" title="<?php echo $title; ?> (<?php echo $year; ?>)"><?php echo $title; ?></a> <small>(<?php echo $year; ?>)</small></p><?php

                                            if ($critics_consensus == "") {?>
                                                <p class="watchlist-synopsis">No overview available</p><?php
                                            } else {?>
                                                <p class="watchlist-synopsis"><?php echo $critics_consensus; ?></p><?php
                                            }?>

                                        </div>
                                    </div>

                                </li><?php
                            }?>

                        </ul>

                    </section>

                    <div id="watchlistUpdate" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="watchlistUpdateLabel" aria-hidden="true">

                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                            <h3 id="watchlistUpdateLabel" class="modal-title">Update Watchlist</h3>
                        </div>

                        <form name="watchlist-updater" class="watchlist-updater" action="watchlist.php?id=<?php echo $watchlist_id; ?>" method='POST'>

                            <div class="modal-body">

                                 <?php echo $updateWatchlist_bad_message; ?>

                                 <div class="alert alert-info">Use the boxes below to change the Watchlist name and description</div>

                                 <input type="text" class="input-block-level" name="watchlist-name" alt="watchlist-name" placeholder="<?php echo $watchlist_name; ?>">
                                 <textarea rows="3" class="input-block-level" name="watchlist-description" title="Watchlist Description" placeholder="<?php echo $watchlist_description; ?>"></textarea>

                                <label for="Watchlist Category" class="pull-left inline-label" title="Watchlist Category">Watchlist Category</label>
                                    <select class="input-block-level" name="watchlist-category" title="Watchlist Category">
                                    <option value="" title=""></option>
                                    <option value="General" title="General">General</option>
                                    <option value="To watch" title="To watch">To watch</option>
                                    <option value="To share" title="To share">To share</option>
                                    <option value="Favourites" title="Favourites">Favourites</option>
                                </select>   

                                 <div class="alert alert-info">Use the checkbox to the left of each film to remove it from the Watchlist</div><?php

                                foreach ($films as $key => $film_item) {
                                    include ("watchlist-film-controller.php");?>    
                                    <label class="checkbox input-block-level">
                                        <p class="pull-right"><?php echo $title; ?></p>
                                        <input type="checkbox" class="input-block-level" name="film-name" value="<?php echo $title; ?>">
                                    </label><?php
                                }?>

                            </div>

                            <div class="modal-footer">
                                <button type="button" class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
                                <button type="submit" class="btn btn-success" name="submit" value="Update Watchlist">Update Watchlist</button>
                            </div>
                        </form>
                    </div>

                    <div id="watchlistDelete" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="watchlistDeleteLabel" aria-hidden="true">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                            <h3 id="watchlistDeleteLabel" class="modal-title">Delete Watchlist</h3>
                        </div>

                        <div class="modal-body">

                            <?php echo $deleteWatchlist_bad_message; ?>

                            <div class="alert alert-error alert-block">
                                 <p>Deleting this Watchlist will delete all its containing films from your profile. This information will not be recoverable.</p>
                                 <p>Please only delete this Watchlist if you are absolutely sure you want to purge all the information it contains.</p>
                             </div>

                              <p>Are you sure you want to delete this Watchlist?</p>

                        </div>

                        <div class="modal-footer">
                            <form name="watchlist-delete" class="watchlist-delete" action="watchlist.php?id=<?php echo $watchlist_id; ?>" method="POST"><?php
                                include ("watchlist-film-controller.php");?>
                                <button type="button" class="btn" data-dismiss="modal" aria-hidden="true">Do not delete this Watchlist</button>
                                <button type="submit" class="btn btn-danger" name="submit" value="Delete Watchlist">Delete Watchlist</button>
                            </form>
                        </div>
                    </div>

                </div>

            </div>

            <?php include 'footer.html'; ?>

        </div>

    </body>

</html>

监视列表的实际更新在#updateWatchlist 模式中。需要更多信息,我很乐意提供!

【问题讨论】:

  • 你会用javascript吗?如果是这样,那么 jQuery 将使这变得非常容易。
  • 问题很难理解:您需要对您对电影观看列表的处理进行彻底的解释:表模式,呈现的 html,以便我们更好地了解什么是行不通的.
  • @didierc 好的,我现在就这样做。帖子应该会在几分钟内用这些新信息更新。
  • @didierc 已按要求更新了完整信息。

标签: php mysql


【解决方案1】:

我认为(其中一个)问题是您正在删除 $rt_id。但是,在前面的那一行中,它只是称为id。除此之外,我现在看不到任何明显的问题。如果这不起作用,请尝试通过将mysql_query 替换为echo 来打印即将发送到数据库的SQL 查询并将输出提供给我们。

另外,一个快速提示:现在,您正在逐一删除电影。根据所选电影的数量,这可能是一个明显的性能打击。一次查询将它们全部删除如何?

if(isset($_POST['film-name'])) {
    $films = array_map('intval', $_POST['film-name']); // make sure that every film id is an integer
    mysql_query("DELETE FROM watchlist_films WHERE film_id IN (" . implode(',', $films) . ")");
}

【讨论】:

  • 谢谢。你能解释为什么在IN 子句中有零是个问题吗?假设 film_id 是自动递增的,那么这些零应该没有任何区别。
【解决方案2】:

一些奇怪的事情:

  1. 在您的删除循环中,您从$checkbox 检查$id,但您使用$rt_id:我认为这是它不起作用的原因。

  2. 对于监视列表描述,您调用clean_string 两次,一次是从$_POST 获取它,另一次是检查它是否为空。

  3. 复选框值实际上是电影标题,而不是电影 ID,您应该修复它,或者在表单处理脚本中检索相应的 ID。

  4. 您删除了具有给定电影 ID 的所有条目,但它可能应该只是与特定观看列表相关联的条目。

关于删除过程,你可以把它变成一个查询:

$range = implode(',', array_filter(
     array_map('intval', $checkbox),
     function($v){ return $v > 0; }));

$update_query = 'DELETE FROM watchlist_films WHERE film_id IN ('.$range.") AND watchlist_id = '" . $watchlist_id."'";

跟着你的cmets,让我详细说明一下:

  1. 您从表单复选框中检索的值是表单生成中称为$title 的值,我想您在watchlist-film-controller.php 中计算它,因为它不会出现在其他任何地方。但是您需要删除表中的行的值是$ rt_id$rt_id 是如何从 $title 计算出来的?

基本上,您的复选框value应该是那个$rt_id,这样在表单处理中,您就不必再次查找该值。我很确定对于给定的电影标题,您可能会获得多个电影 ID,因此您不能仅仅依靠标题来删除监视列表中的条目。想象一下,有人在她的关注列表中拥有所有名为“True Grit”的电影,如果她选择删除其中一部,你会如何处理?

请考虑将来将您的代码移至 PDO 或 mysqli API,以实现更安全的数据清理。

【讨论】:

  • 谢谢,但这似乎也不起作用(请原谅我,我还是个 PHP 新手!)。我已经用新信息更新了原始帖子,以防万一。
猜你喜欢
  • 2019-08-24
  • 2012-02-10
  • 1970-01-01
  • 1970-01-01
  • 2012-09-15
  • 1970-01-01
  • 1970-01-01
  • 2017-12-16
  • 1970-01-01
相关资源
最近更新 更多