簡體   English   中英

使用復選框從表中刪除行

[英]Delete rows from table using checkboxes

我試圖基於復選框從表中刪除多行,但是我不太確定如何最好地解決它。 目前,我有一部電影列表,並且我希望能夠根據是否已選擇來刪除其中一部或多部電影。

// 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刪除帶有多個復選框的SQL行 -但是,由於電影沒有從其包含的監視列表中刪除,因此它不起作用。

基本上,查詢的邏輯如下:

  • 檢查是否選中了一個復選框
  • 如果勾選了一個復選框,請檢查是否也勾選了其他復選框
  • 從監視列表中刪除所有已勾選的電影

我不確定以上是否是最簡單的方法,例如,檢查是否勾選了多個復選框可能更簡單,更干凈,而不是先檢查是否勾選了任何復選框,然后再進行檢查如果其他人也是如此。

UPDATE

只是想我將提供更多信息來闡明-下面顯示了我在監視列表中顯示的所有電影的實際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

為了回答這篇文章中的兩個(非常感謝!)評論,這里有更多有關當前情況的信息。 我已經嘗試過兩種解決方案,但是都沒有用。 就目前而言,我已經實現了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_films watchlists包含簡單的信息,例如監視列表ID,名稱和描述,以及創建監視列表的用戶的用戶ID。 watchlist_films僅包含監視列表ID和監視列表包含的電影ID( $rt_id )。 甲監視列表占用在單個行watchlists在表中和多個行watchlist_films表(作為一個監視列表可以有多個膜)。
  • 電影信息是從Rotten Tomatoes和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模式中。 需要更多信息,我很樂意提供!

我認為問題之一是您正在通過$rt_id刪除。 但是,在前面的行中,它僅稱為id 除此之外,我現在看不到任何明顯的問題。 如果那不起作用,請嘗試將要發送到數據庫的SQL查詢打印出來,方法是將mysql_query替換為echo並提供給我們輸出。

另外,還有一個快速提示:現在,您正在逐部刪除電影。 根據所選擇的電影數量,這可能會引起明顯的性能影響。 如何在一個查詢中將它們全部刪除?

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) . ")");
}

一些奇怪的事情:

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

在您發表評論后,讓我詳細說明:

  1. 從表單復選框中檢索到的值在表單生成中稱為$title ,我想您在watchlist-film-controller.php計算該值,因為它在其他任何地方都沒有出現。 但是您需要刪除表中的行的值為$ rt_id 如何從該$title計算$rt_id

基本上,您的復選框value 應為 $rt_id ,以便在表單處理中,您不必再次查找該值。 我非常確定,對於給定的電影標題,您可能會獲得多個電影ID,因此您不能僅僅依靠標題來刪除監視列表中的條目。 假設某人的監視列表中有所有名為“ True Grit”的電影,如果她選擇刪除其中一部,您將如何處理?

請考慮將來將代碼移至PDO或mysqli API,以實現更安全的數據清理。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM