简体   繁体   中英

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.

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

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 ($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

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:

<?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. 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. 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

In response to didierc's comment, here's a full breakdown of what's going on:

  • Watchlists are broken down into two tables - watchlists and watchlist_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. watchlist_films only contains the Watchlist ID and the film IDs the Watchlist contains ( $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).
  • 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 .

The full 'processing code' for Watchlists is in Update 2 , however the HTML rendering is as follows:

<?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. Anymore information required, I'm happy to provide!

I assume that (one of) the problem(s?) is that you're deleting by $rt_id . However, in the line before, it is just called 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.

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.

  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.

  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.

  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.

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. But the value you need to delete the row in your table is $ rt_id . How is $rt_id computed from that $title ?

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. 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. 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?

Please think about moving your code to the PDO or mysqli API in the future, to enable safer data sanitization.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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