简体   繁体   English

使用复选框从表中删除行

[英]Delete rows from table using checkboxes

I am trying to delete multiple rows from a table based on checkboxes, however I'm not too sure how best to go about it. 我试图基于复选框从表中删除多行,但是我不太确定如何最好地解决它。 Currently, I have a list of films, and I want to be able to delete one or more of these films, based on whether they have been selected. 目前,我有一部电影列表,并且我希望能够根据是否已选择来删除其中一部或多部电影。

// 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
    }

The appropriate string is the film-name, and I have attempted to use this solution - PHP to delete SQL row with multiple checkboxes - however it is not working, insofar as the films are not being deleted from their containing Watchlist. 适当的字符串是电影名称,并且我尝试使用此解决方案-PHP删除带有多个复选框的SQL行 -但是,由于电影没有从其包含的监视列表中删除,因此它不起作用。

Basically, the logic behind my query is as follows: 基本上,查询的逻辑如下:

  • check if one checkbox is ticked 检查是否选中了一个复选框
  • if one checkbox is ticked, check if any others are ticked, too 如果勾选了一个复选框,请检查是否也勾选了其他复选框
  • delete all films from the Watchlist which have been ticked 从监视列表中删除所有已勾选的电影

I'm not sure if the above is the easiest way to do it, for example, it may be simpler and cleaner to just check if any checkboxes are ticked in one big go, rather than checking first if any one has been ticked before checking if others have been, too. 我不确定以上是否是最简单的方法,例如,检查是否勾选了多个复选框可能更简单,更干净,而不是先检查是否勾选了任何复选框,然后再进行检查如果其他人也是如此。

UPDATE UPDATE

Just thought I'd clarify with more info - my actual foreach showing all the films in the Watchlist, is below (apologies for the formatting): 只是想我将提供更多信息来阐明-下面显示了我在监视列表中显示的所有电影的实际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
}

UPDATE 2 更新2

In answer to the two (gratefully received!) comments on this post, here's a little more information about what's now happening. 为了回答这篇文章中的两个(非常感谢!)评论,这里有更多有关当前情况的信息。 I've tried both solutions, however neither are working. 我已经尝试过两种解决方案,但是都没有用。 As it stands, I have implemented the solution given by didierc and my code currently looks like this: 就目前而言,我已经实现了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 is each film's unique ID and is being passed to the form, so the query knows which film or films, in this case, should be deleted. $rt_id是每部电影的唯一ID,并会传递给表单,因此查询知道在这种情况下应删除哪部电影。 The name of the film is only being used to make the actual delete form more human-readable, rather than printing out a list of ID numbers, as the user would have no way of knowing which ID matched which film. 影片的名称仅用于使实际的删除形式更易于阅读,而不是打印ID号列表,因为用户将无法知道哪个ID与哪部影片匹配。 After trying out both solutions given, neither appears to be working, however no errors are being returned - the form submits, but the selected films do not delete from the Watchlist. 在尝试了给出的两种解决方案后,它们似乎都没有起作用,但是没有错误返回-表单已提交,但是所选影片不会从监视列表中删除。

Update 3 更新3

In response to didierc's comment, here's a full breakdown of what's going on: 为了回应Didierc的评论,以下是发生了什么的完整分解:

  • Watchlists are broken down into two tables - watchlists and watchlist_films . 监视列表分为两个表- watchlistswatchlist_films watchlists holds simple information such as the Watchlist ID, name and description, as well as the user ID of the user who created it. watchlists包含简单的信息,例如监视列表ID,名称和描述,以及创建监视列表的用户的用户ID。 watchlist_films only contains the Watchlist ID and the film IDs the Watchlist contains ( $rt_id ). watchlist_films仅包含监视列表ID和监视列表包含的电影ID( $rt_id )。 A Watchlist takes up a single row in the watchlists table and multiple rows in the watchlist_films table (as one Watchlist can have multiple films). 甲监视列表占用在单个行watchlists在表中和多个行watchlist_films表(作为一个监视列表可以有多个膜)。
  • Film information is being brought back from the Rotten Tomatoes and TMDb APIs, and this is where the film ID ( $rt_id ) is from - each film has a completely unique $rt_id . 电影信息是从Rotten Tomatoes和TMDb API中获取的,这就是电影ID( $rt_id )的来源-每部电影都有一个完全唯一的$rt_id

The full 'processing code' for Watchlists is in Update 2 , however the HTML rendering is as follows: 监视列表的完整“处理代码”在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>

The actual updating of the Watchlist is in the #updateWatchlist modal. 监视列表的实际更新在#updateWatchlist模式中。 Anymore information required, I'm happy to provide! 需要更多信息,我很乐意提供!

I assume that (one of) the problem(s?) is that you're deleting by $rt_id . 我认为问题之一是您正在通过$rt_id删除。 However, in the line before, it is just called id . 但是,在前面的行中,它仅称为id Other than that, I can't see any obvious problems right now. 除此之外,我现在看不到任何明显的问题。 If that doesn't work, please try to print the SQL query as it is about to be sent to the database by replacing mysql_query with echo and give us the output. 如果那不起作用,请尝试将要发送到数据库的SQL查询打印出来,方法是将mysql_query替换为echo并提供给我们输出。

Also, a quick tip: Right now, you are deleting the films one by one. 另外,还有一个快速提示:现在,您正在逐部删除电影。 Depending on the number of films selected, this might be a noticeable performance hit. 根据所选择的电影数量,这可能会引起明显的性能影响。 How about you delete them all in one 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) . ")");
}

Some odd things: 一些奇怪的事情:

  1. in your delete loop you check $id from $checkbox , yet you use $rt_id : I think it's the reason why it doesn't work. 在您的删除循环中,您从$checkbox检查了$id ,但是您使用了$rt_id :我认为这是它不起作用的原因。

  2. for watchlist-description, you call clean_string twice on it, once when you get it from $_POST and another time when you check if it's empty. 对于监视列表描述,您可以在其上调用clean_string两次,一次是从$_POST获取一次,另一次是检查其是否为空。

  3. the checkbox values are actually the movie titles, not the movie ids, you should probably fix that, or retrieve the corresponding id in the form process script. 复选框值实际上是电影标题,而不是电影ID,您可能应该解决该问题,或在表单流程脚本中检索相应的ID。

  4. you delete all the entries with a given film id, but it should probably be only the ones tied to a specific watch list. 您将删除具有给定影片ID的所有条目,但可能应该仅是与特定观看列表相关的条目。

Regarding the delete process, you can make it into one single query: 关于删除过程,您可以使其成为一个查询:

$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."'";

Following your comments, let me elaborate: 在您发表评论后,让我详细说明:

  1. The value you retrieve from the form checkbox is something called $title in the form generation, which I suppose you compute in watchlist-film-controller.php , since it doesn't appear anywhere else. 从表单复选框中检索到的值在表单生成中称为$title ,我想您在watchlist-film-controller.php计算该值,因为它在其他任何地方都没有出现。 But the value you need to delete the row in your table is $ rt_id . 但是您需要删除表中的行的值为$ rt_id How is $rt_id computed from that $title ? 如何从该$title计算$rt_id

Basically, your checkbox value should be that $rt_id , so that in the form processing, you don't have to look up the value again. 基本上,您的复选框value 应为 $rt_id ,以便在表单处理中,您不必再次查找该值。 I'm pretty sure that for a given movie title, you may get several movie id, so you cannot rely simply on the title to delete an entry in the watchlist. 我非常确定,对于给定的电影标题,您可能会获得多个电影ID,因此您不能仅仅依靠标题来删除监视列表中的条目。 Imagine that someone has all the movies named "True Grit" in her watchlist, how would you handle it, if she choose to delete one of them? 假设某人的监视列表中有所有名为“ True Grit”的电影,如果她选择删除其中一部,您将如何处理?

Please think about moving your code to the PDO or mysqli API in the future, to enable safer data sanitization. 请考虑将来将代码移至PDO或mysqli API,以实现更安全的数据清理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM