This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 3 years ago.
i am working on website with buttons each button fire up a bootstrap modal contain data from mysql database i pass a variable from the jquery that fire up the model into a mysql query inside the modal the problam is the php variable cannot get the data send it from the jquery any hints please ?!
i am passing data through jquery post to ajax.php file
the modal code
<div class="modal" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<span id="codeElem"></span>
<?php
$resultHead = mysqli_query($con2,"SELECT * FROM coops WHERE Code = $getCode ");// WHERE Code IN ('".$codeArrayStr."')
?>
<?php
$i=0;
$row3 = mysqli_fetch_array($resultHead);
?>
<h4 class="modal-title"><?=$row3['CoopName'];?></h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<!-- Modal body -->
<div class="modal-body">
<?php
$result = mysqli_query($con,"SELECT DISTINCT * FROM reports WHERE host = $getCode GROUP BY host DESC");
?>
<?php
$i=0;
while($row = mysqli_fetch_array($result)) {
?>
<div class="card card-figure has-hoverable">
<figure class="figure">
<img class="img-fluid" src="http://www.iroof.tv/screenshots/<?=$row['screenshot'];?>" alt="Card image cap">
<figcaption class="figure-caption">
<h6 class="figure-title"><?=$row['host'];?></h6>
<p class="text-muted mb-0"> <?=$row['timestamp'];?> </p>
<?php
// Assign JSON encoded string to a PHP variable
$statusJson = $row['status'];
// Decode JSON data into PHP associative array format
$arr = json_decode($statusJson, true);
// Call the function and print all the values
// $result2 = printValues($arr);
echo "<hr>";
echo "<h3> Player </h3>";
// Print a single value
echo "Status: ".$arr["player"]["status"] . "<br>";
echo $arr["player"]["filename"] . "<br>";
echo "<hr>";
echo "<h3> Graphics </h3>";
echo "Display: ".$arr["video"]["display"] . "<br>";
echo "Resolution: ".$arr["video"]["resolution"] . "<br>";
echo "Colors: ".$arr["video"]["colors"] . "<br>";
echo "<hr>";
echo "<h3> System </h3>";
echo "CPU: ".$arr["cpu"] . "<br>";
echo "Ram: ".$arr["ram"] . "<br>";
//echo "Temprature: ".$arr["temperature"] . "<br>";
echo "Fan: ".$arr["fan"] . "<br>";
?>
</figcaption>
</figure>
</div>
<?php $i++;
}
?>
</div>
<!-- Modal footer
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>-->
</div>
the jquery script
<script>
$(document).ready(
function() {
setInterval(function() {
$('.card');
}, 5000); //Delay here = 5 seconds
var gen;
$(".btn").click(function(){
gen = $(this).attr("data-code");
//$.post("ajax.php", {"code": gen},function(data){console.log(data);});
});
$('#myModal').on('shown.bs.modal', function () {
$.post("ajax.php", {"code": gen},function(data){console.log(data);});
//var phpCode = "<? $getCode = $_POST["code"]; ?>";
//$('#codeElem').html(phpCode);
})
});
</script>
ajax.php file
<?php
if(isset($_POST['code']) && isset($_POST['code'])){
//$_SESSION["code"] = $_POST["code"];
$_SESSION['header'] = $_POST['code'];
$getCode = $_POST["code"];
echo $_SESSION['header'];
}
?>
i expect the variable $getCode to get the code from jquery to complete the mysql query inside the modal :
$resultHead = mysqli_query($con2,"SELECT * FROM coops WHERE Code = $getCode");
I dont think its possible to post variables to a modal, I didnt see example like that when I was searching for popup modal login.
guess you need an action page to forvard infos to modal.
This is the solution to post variables:
Change variables to your needs..
$(document).ready(function(){
$("form").submit(function(event){
event.preventDefault();
var post_id =$("#mail-id").val();
var name =$("#mail-name").val();
var email =$("#mail-email").val();
var message =$("#mail-message").val();
var type =$("#mail-type").val();
var captcha_code =$("#captcha_code").val();
var submit =$("#mail-submit").val();
$(".form-message").load("heads/comment.php",{
post_id: post_id,
name: name,
email: email,
message: message,
type: type,
captcha_code: captcha_code,
submit: submit
});
});
});
you probably need some thing like this to show variables in popup
<p class="form-message"></p>
Or you can check Bootstrap modal table :
Here
I've looked extensively and still haven't found the answer to my question. I've gotten close, but I think that's as far as I can get on my own.
I have a database that has tables for different years, like so:
year_2016,
year_2017,
year_2018,
etc...
I'm using PHP and MySQL to query these tables and using AngularJS to display them in HTML.
Here is my HTML:
<div id="main" ng-controller="MyController">
<input type="text" placeholder="Search" autofocus ng-model="query" />
<input type="text" placeholder="Year" ng-model="year" ng-blur="sendData()" />
<div id="db-results" ng-show="query">
<p><span>Searching for: "{{ query }}"</span></p>
<p>{{ filtered.length }} results</p>
<div class="container table">
<div class="row" ng-repeat="item in items | limitTo : 100 | filter : query as filtered">
<div class="col bg-info text-light rounded-left">{{ item.dir }}</div>
<div class="col bg-warning text-dark">{{ item.index }}</div>
<div class="col-lg-6 bg-light text-dark">{{ item.text }}</div>
</div><!-- row -->
</div><!-- table -->
</div><!-- db-results -->
</div><!-- main -->
And my Angular:
var myControllers = angular.module('myControllers', []);
myControllers.controller('MyController',
function MyController($scope, $http) {
$scope.year = 2018;
$scope.sendData = (function () {
var data = $.param({
year: $scope.year
});
var config = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8;'
}
};
var postURL = 'mysql_conn.php';
$http.post(postURL, data, config)
.then(
function(response){
console.log(data);
console.log('post_year=' + response.data.year);
$scope.items = response.data.records;
},
function(response){
console.log('failure ' + response);
});
})();
});
And finally, the PHP:
<?php
header("Access-Control-Allow-Origin: *");
$request = json_decode(file_get_contents('php://input', true));
$year = $request->year;
// $year = 2018;
$conn = new mysqli("SERVER", "USER", "PASSWORD", "DATABASE");
$result = $conn->query("SELECT * FROM year_" . $year . " LIMIT 100;");
$output = "";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
if ($output != "") {$output .= ",";}
$output .= '{"dir":"' . $rs["dir_index"] . '",';
$output .= '"index":"' . $rs["sub_index"] . '",';
$output .= '"text":"' . $rs["text"] . '"}';
}
$output ='{"records":[' . $output . '], "year": ' . $year . '}';
$conn->close();
echo($output);
?>
I can set the $year variable in PHP statically and it queries everything from the table corresponding to that year, and then on my actual web page, I can type in a search and it will filter the records accordingly. That much works.
What I want to be able to, that I can't do already, is type in the year in the year input box and have the PHP re-query the appropriate table and display the results. In other words, I want the year input box to be responsive. PHP is not dynamic, so I thought Angular/AJAX might be able to help me out here.
In the Angular code, I am using http.post to send the value of $scope.year to PHP to then query the corresponding table. At least, that's what I'm trying to do. It's not working. In PHP, part of the output JSON is the $year variable that should be identical to the $scope.year model, but when I print it to the console in Angular, it returns undefined. I'm also using the same POST request to get the data that PHP queries from the database (this works).
I had also tried using separate GET and POST requests but this didn't work.
Thanks!
I'm trying to learn php, mysql and javascript/jquery by building a live bidding system. I want to refresh the value of a bid button and dropdown automatically, but only if the value has changed. I've made a bidbuttons.php that outputs the buttons after querying the db for the current values, and I load and reload the page with this jquery I found elsewhere. I have tried several different methods of refreshing the div, and the best I came up with unfortunately closed the dropdown on the timer. This current version was described as exactly what I need but doesn't seem to work, in fact it logs me out. would prefer the div to refresh and the dropdown to close ONLY if the bidbuttons.php is updated. This is my first post, I hope I did this right.
<div id="bidbuttons"></div>
<script type="text/javascript">
var loadUrl = "includes/bidbuttons.php?id='.$item->id.'";
$("#bidbuttons").load(loadUrl).fadeIn("slow");
var auto_refresh = setInterval(function () {
$.get(loadUrl, function(data) {
if (data.changed) {
$("#bidbuttons").load(loadUrl).fadeIn("slow");
}
});
}, 10000);
</script>
and my bidbuttons.php
<?php
include_once 'db_connect.php';
include_once 'functions.php';
sec_session_start();
if (login_check($mysqli) == true) {
$getid = (int)$_GET['id'];
// get current price
$result = $mysqli->query("SELECT ammount, bidder_id FROM bids WHERE ammount=(SELECT MAX(ammount)) && item_id like $getid order by ammount desc");
while($row = $result->fetch_assoc()) {
$bidder_id = $row["bidder_id"];
$current = $row['ammount'];
echo ($mysqli->error);
$result->free();
}
//get item info
$results = $mysqli->query("SELECT * FROM items WHERE id like $getid ");
while($row = $results->fetch_assoc()) {
if (empty ($current)) { $current = $row["start"];}
$title = $row["title"];
$item->thenext = ($current + $row["raise"]);
$buyout = $row["buyout"];
$raise = $row["raise"];
$sold = $row["sold"];
}
$results->free();
echo ('<div id="buttons">
<a class="btn btn-primary btn-lg" style="margin-bottom: 10px; margin-top: 10px; width: 80%;" href="includes\placebid.php?itemid=' . $getid . '&ammount=' . $item->thenext .'">Bid $' . $item->thenext . '</a>
');
if ($buyout){echo ('
<a class="btn btn-success btn-lg" style="margin-bottom: 10px; width: 80%;" href="includes\placebid.php?itemid='.$getid.'&ammount='.$buyout.'">Buyout $'.$buyout.'</a>
');}
echo '</div><!-- buttons -->';
echo ('
<div class="dropdown">
<button style="margin-bottom: 10px; width: 80%;" type="button" class="btn btn-info btn-lg dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Custom Bid<span class="caret"></span></button>
<ul class="dropdown-menu">
');
// build the custom bid dropdown
if (!$buyout) { $maxcust = $item->thenext*25;
for ($cust = $item->thenext; $cust <= $maxcust; $cust = $cust + $raise) {
echo ('<li>' .$cust. '</li>');
}
}
if ($buyout) {
for ($cust = $item->thenext; $cust <= $buyout; $cust = $cust + $raise) {
echo ('<li>' .$cust. '</li>');
}
}
echo ('
</ul>
</div><!-- dropdown -->
');
}
mysqli_close($mysqli);
?>
I think the problem may be in that your PHP file is generating HTML which is continually replacing elements on your page due to them being loaded via AJAX.
Just an idea but you could make your PHP output a JSON instead that contains the database results, then have jQuery read the output. Your code would then process that JSON file and create or update the HTML elements accordingly (rather than replace them).
This way you have more fine grained control in the JavaScript for when your dropdown should close.
See this answer if you'd like to output from MySQLi to JSON.
I am trying to make tabs that contain information about student, these information is stored in the database. I want the first tab to show the information of all students. and the the second tab to show the information of the students that thier grade is A and the the third tab to show the information of the students that thier grade is B.
I made this code but just the first tab shows the information of the students but the second and third tabs don't show anything.
what is wrong with the code?
<html>
<head>
<title>students table</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<script>
$(function() {
$( "#tabs" ).tabs();
});
</script>
</head>
<body>
<div id="tabs">
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
<?php
$connection = mysql_connect("","","");
if (!$connection)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("", $connection);
$result = mysql_query("SELECT * FROM studentTable");
while($row = mysql_fetch_array($result))
{
?>
<div id="tabs-1">
<?php
echo "Student id: '" . $row["id"];
echo "Student name: '" . $row["name"];
echo "Student grade: '" . $row["grade"];
echo '</table>';
}
?>
</div>
<?Php
$result2 = mysql_query("SELECT * FROM studentTable WHERE grade = 'A'");
while($row = mysql_fetch_array($result2))
{
?>
<div id="tabs-2">
<?php
echo "Student id: '" . $row["id"];
echo "Student name: '" . $row["name"];
echo "Student grade: '" . $row["grade"];
echo '</table>';
}
?>
</div>
<?php
$result3 = mysql_query("SELECT * FROM studentTable WHERE grade = 'B'");
while($row = mysql_fetch_array($result3))
{
?>
<div id="tabs-3">
<?php
echo "Student id: '" . $row["id"];
echo "Student name: '" . $row["name"];
echo "Student grade: '" . $row["grade"];
echo '</table>';
}
?>
</div>
</div>
</body>
</html>
I think your issue is because you have your tabs-# <div> opening tags inside your while() loops.
$result = mysql_query("SELECT * FROM studentTable");
while($row = mysql_fetch_array($result))
{
?>
<div id="tabs-1"> //this here needs to be above/outside while($row = mysql_fetch_array($result)){
This is creating n number of <div id="tabs-1">,<div id="tabs-2">,<div id="tabs-3">, without matching closing tags </div>, so now <div id="tabs-2"> & <div id="tabs-3"> are nested in <div id="tabs-1"> and jQuery doesn't know which one to bind tabs to.
try moving them before the while() loops -
<div id="tabs-1">
<?php
$result = mysql_query("SELECT * FROM studentTable");
while($row = mysql_fetch_array($result))
{
...
}
?>
</div>
<div id="tabs-2">
<?php
$result2 = mysql_query("SELECT * FROM studentTable WHERE grade = 'A'");
while($row = mysql_fetch_array($result2))
{
...
}
?>
</div>
<div id="tabs-3">
<?php
$result3 = mysql_query("SELECT * FROM studentTable WHERE grade = 'B'");
while($row = mysql_fetch_array($result3))
{
...
}
?>
</div>
Also, you have echo '</table>'; at the end of each tab div. May want to remove those if you don't actually have a table.
In your script you are trying to use Jquery's tab method.
<script>
$(function() {
$( "#tabs" ).tabs();
});
</script>
This is looking in the HTML for
<div id='tabs'>
You're tabs in here
</div>
Assuming that your SQL statments is not returing "NULL" then I would say you're issue is that you named you're div's tab-1, tab-2, tab-3. With ID's. This means that Jquery can't find anything to turn into tab's.
Change your jquery call to something like this
<script>
$(function() {
$( ".tabsclass" ).tabs();
});
</script>
and instead of using id's use classes.
<div class='tabsclass' id='tab-1'>
You're tabs in here
</div>
<div class='tabsclass' id='tab-2'>
You're tabs in here
</div>
<div class='tabsclass' id='tab-3'>
You're tabs in here
</div>
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>
Update Watchlist
Delete Watchlist
Your Profile
</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">
<img src="<?php echo $poster_thumb; ?>" alt="<?php echo $title; ?> poster" title="<?php echo $title; ?> poster" />
<div class="span11 movie-info">
<p class="search-title"><?php echo $title; ?> <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:
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.
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.
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.
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:
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.