Delete rows from table using checkboxes - php

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.

Related

updating sql with php

I need to be able to update my sql table from open to close task.
I already wrote code for this but it is not working properly. On the modal it shows 2 'continue' buttons and right now the task table contains two tasks. Can somebody help me?
This is what the modal looks like:
and this is my code:
<?php
if (isset($_POST["closetask"])) {
$close_task_id = mysqli_real_escape_string($con, $_POST["close_task_id"]);
$sql = "UPDATE task SET task_status='closed' WHERE id_task='$close_task_id'";
$result = mysqli_query($con, $sql);
if ($result) {
$_SESSION['success'] = "Task closed";
$_SESSION['text'] = "Task has been closed successfully";
$_SESSION['icon'] = "success";
} else {
$_SESSION['success'] = "Error";
$_SESSION['text'] = "Unkown error, please try again";
$_SESSION['icon'] = "error";
}
}
?>
<?php
$query = "SELECT * FROM task ORDER BY id_task DESC";
$result = mysqli_query($con, $query);
?>
<!-- reject button -->
<form action="task-view.php" method="post" enctype="multipart/form-data">
<div id="rejectModal" class="modal fade" role="dialog" >
<div class="modal-dialog modal-lg">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Close this task?</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
<div class="d-flex align-items-center justify-content-center form-group" >
<p class="align-items-center text-center" for="company">This button means closing the task. Are you sure you want to continue?</p>
</div>
</div>
<div class="modal-footer">
<?php
while ($row = mysqli_fetch_array($result)) {
if ($row['task_status'] == 'open'){
$check_task = '
<input type="text" name="close_task_id" class="form-control" value="' . $row["id_task"] . '" hidden>
<button class="btn btn-success" type="submit" name="closetask" class="btn btn-success">Continue</button>
</button>
';
}
echo '
<br>
' . $check_task . '
';
}
?>
</div>
</div>
</div>
</div>
</div>
</form>
<!-- end of reject button-->
<?php
if (isset($_SESSION['success']) && $_SESSION['success'] != '') {
?>
<script>
swal({
title: "<?php echo $_SESSION['success']; ?>",
text: "<?php echo $_SESSION['text']; ?>",
icon: "<?php echo $_SESSION['icon']; ?>",
button: "OK",
});
</script>
<?php
unset($_SESSION['success']);
}
?>
Well, after going through your code snippet,
I could see this query
$query = "SELECT * FROM task ORDER BY id_task DESC";
$result = mysqli_query($con, $query);
meaning this fetches all records in the task table, the two continue buttons you see are coming from the while loop
while ($row = mysqli_fetch_array($result)) {
....
}
it logically implies you have two records or rows in your database task table and all the records where retrieved from the table.

Ajax not redirecting me to next page

I am trying to pass the ID of the clicked image to next page. When I developed my code, it didn't redirect me to the next page. When I click F12 and check the POST in network, it shows that the variable is passed correctly to the next page as shown in the attached image but it didn't redirect me to the next page. So now I know that the variable is passed and received correctly in the next page but I need what needed in my code to direct me to the next page,
Note: when I tried to put window.location.href = 'userevent.php'; it redirect me but without the variable and gives me error (Notice: Undefined index: clicked in)
Also when I use url: '#userevent.php.Action("delivery", "service")',, it gives me network status 403
this is my code:
<?php
session_start();
require "init.php";
login();
?>
<html>
<!--...-->
<head>
<meta charset="utf-8">
<title> Ghost </title>
<!-- <link rel="Stylesheet" href="css/style1.css">-->
<link rel="stylesheet" href="css/style2.css" media="screen" type="text/css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script >
function myFunction(clicked) {
document.getElementById('test').innerHTML = clicked;
$.ajax({
type: "POST",
//url: '#userevent.php.Action("delivery", "service")',
url: 'userevent.php',
dataType:'json',
data: {"clicked": clicked},
success: function(data){
}
});
window.location.href = 'userevent.php';
}
</script>
</head>
<body>
<div class="sidenav">
Main Page
About Us
</div>
<div class="login-box">
<h1>Add Event</h1>
<div>
<p id="test"> </p>
<?php
// LOGIN USER
function login(){
global $con;
global $counter;
echo "<table align='center' >";
//$email = $mysqli->escape_string('');
$query="SELECT * FROM events ORDER BY ID ASC";
$result=mysqli_query($con,$query);
if ( $result->num_rows == 0 ) // User doesn't exist
echo "User with that ID doesn't exist!";
else { // User exists
$counter = 0;
$emptyArray = [];
while($row = $result->fetch_assoc())
{
$emptyArray[$counter]= $row["ID"];
if($counter == 0)
{
echo '<tr>';
}
echo '<td><img id=' . $row["ID"]. ' onClick="myFunction(this.id)" src="images/' . $row["photo"]. '" width="250px" height= "250px" alt="Avatar" >
<h1 id = "GFG_DOWN" style =
"color:white;text-align:center; font-size: 20px; font-weight: bold;"> '.$emptyArray[$counter].'
</h1> </td>';
$counter++;
if($counter == 3)
{
echo "</tr>";
$counter = 0;
}
}
}
}
mysqli_close($con);
?>
and this is the code in the second page:
<div class='textbox'>
<label> ID: ".$_POST['clicked']."</label>
</div>
The entire point of Ajax is that that request is made with JavaScript and the response is handled by JavaScript without navigating to a new page.
If you want to make a POST request and navigate to the resulting page, then use a <form>
window.location.href = 'userevent.php';
it redirect me but without the variable
Assigning a URL to location.href triggers browser navigation (with a GET request) to that URL.
It is a completely different request to the Ajax request so it doesn't have the data from that request.
Again: Use a form for this.
I read the data from database and I get the clicked id of the images.
Put the data you want to send in a submit button instead.
<form method="POST" action="userevent.php">
<?php while($row = $result->fetch_assoc()) ?>
<button name="clicked" value="<?php echo htmlspecialchars($row["ID"]); ?>">
<img src="images/<?php echo htmlspecialchars($row["photo"]); ?> alt="Put useful and unique alt text so people know what they are selecting if they can't see the image">
</button>
<?php } ?>
</form>
I think you are better off making a small form, since you want to send the user to a new page when clicking.
<?php while($row = $result->fetch_assoc()) ?>
<form action="userevent.php" method="POST">
<input type="hidden" name="clicked" value="$row["ID"]">
<img src="images/{{ $row['photo'] }}" class="img">
</form>
<?php } ?>
$('.img').click(function() {
this.form.submit();
});
*Edited to reflect your current edits.

assign value to php variable using jquery [duplicate]

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

Pulling the user's ID number from database (depending on the logged in user)

So my user's have access to changing their custom notify which is stored in my 'clients' database as 'notify'. I cannot seem to find out how to pull this information per session (as I don't want another user to change someone else's notify. Basically I'm trying to allow the user to click "Change Notify" in the navigation menu, then their notify (which I am guessing will depend on their session ID) shows up in the notify textbox, which will allow them to edit it accordingly.
This is my session starting php
<?php
include "includes/settings.php";
include "includes/database.php";
if(!isset($_SESSION))
{
session_start();
echo "Welcome=" . $_SESSION['id'];
}
if(!isset($_SESSION['username']))
{
echo'
<script language="javascript">
window.location.href="index.php"
</script>
';
}
$usersrow = mysqli_query($con, "SELECT COUNT(1) FROM `users`");
$user_row = mysqli_fetch_array($usersrow);
$user_total = $user_row[0];
$clients = mysqli_query($con, "SELECT COUNT(1) FROM `clients`");
$clients_row = mysqli_fetch_array($clients);
$clients_total = $clients_row[0];
$time_now = time("Y-m-d");
if(isset($_GET['deleteclient']))
{
if($_GET['deleteclient'])
{
$id = strip_tags($_GET['deleteclient']);
mysqli_query($con, "DELETE FROM `clients` WHERE `id` = '$id'") or die(mysqli_error($con));
}
}
?>
This is my update notify php
<?php
if(isset($_POST['upduser']))
{
$clientnotify = $_POST['notifyVal'];
$update_now = mysqli_query($con, "UPDATE `clients` SET `notify`='$clientnotify' WHERE `notify` = '".$client_notify."'");
if($update_now)
{
echo'<div class="row"><div class="col-md-12"><div class="alert alert-success">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">x</button>
<strong>OK!</strong> Client successfully updated!.
</div></div></div>';
echo '<meta http-equiv="refresh" content="1;url="dashboard.php">';
}
elseif(!$update_now)
{
echo'<div class="row"><div class="col-md-12"><div class="alert alert-danger">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">x</button>
<strong>Fail!</strong> Client not update, Try again!.
</div></div></div>
';
}
}
?>
This is my Custom Notify Form
<div class="panel panel-info">
<form method="POST">
<div class="panel-heading">
<h3 class="panel-title">SET CUSTOM NOTIFY</h3>
</div>
<div class="panel-body controls no-padding">
<div class="row-form">
<div class="col-md-3"><strong>Notify : </strong></div>
<div class="col-md-9"><input type="text" required class="form-control" value = "<?php echo $client_notify; ?>" placeholder="Notify" name="notifyVal"/></div>
</div>
</div>
<div class="panel-footer">
<button class="btn btn-success" name="updnotify">Set Custom Notify</button>
</div>
</form>
</div>
Any help would be appreciated.

Update dynamic lists php mysql Javascript

I have 2 lists, one for companies and one for sites. Each company has different sites around the country. I am am displaying 2 lists side by side on a modal popup. I have the companies list displaying dynamically from a query all ok, I want the second list to populate with the sites, depending on the company selection from the first list.
image of both lists side by side as I have it
The html element is as follows:
<div class="row">
<div class="col-md-6">
<div class="container-fluid">
<div style="height: 400px; overflow-y: scroll">
<div class="list-group" name="companies" id="company">
<!--Call the Showcompany() method from the select.class.php-->
<?php echo $opt->ShowCompany(); ?>
</div>
</div><!--End of first input group-->
</div><!--End of container-->
</div><!--End of column-->
<div class="col-md-6">
<div class="container-fluid">
<div style="height: 400px; overflow-y: scroll">
<div class="list-group" multiple onchange="changeSelection(this.value)" name="sites" id="sites">
<?php echo $opt->ShowSite(); ?>
</div>
</div><!--End of first input group-->
</div><!--End of container-->
</div><!--End of column-->
</div>
This is being populated from a separate included php file as follows:
//function to handle db connectivity
protected function DbConnect()
{
include "db_config.php";
$this->conn = mysql_connect($host,$user,$password) OR die("Unable to connect to the database");
mysql_select_db($db,$this->conn) OR die("can not select the database $db");
return TRUE;
}
//function to query the companies and return list for companies list
public function ShowCompany()
{
$sql = "SELECT company.company_name, company.id FROM company ORDER BY company.company_name ASC";
$res = mysql_query($sql,$this->conn);
$company = '<a class="list-group-item active" value="0">choose...</a>';
while($row = mysql_fetch_array($res))
{
$company .= '<a class="list-group-item" value="' . $row['id'] . '">' . $row['company_name'] . '</a>';
}
return $company;
}
//function to query the sites and return list for sites list
public function ShowSite()
{
$sql = "SELECT * FROM sites WHERE company_id=$_POST[id]";
$res = mysql_query($sql,$this->conn);
$site = '<a class="list-group-item" value="0">Select All</a>';
while($row = mysql_fetch_array($res))
{
$site .= '<a class="list-group-item" value="' . $row['id'] . '">' . $row['site_name'] . '</a>';
}
return $site;
}
The jquery I am using to try and populate the second list is as follows this is in my document.ready function.
$("#company").change(function(){
var id = $("#company a:selected").attr('value');
$.post("select_site.php", {id:id}, function(data){
$("#sites").html(data);
});
});
I have had this working when I used select dropdowns and instead of anchor tags I had option tags and it all worked, but it never looked right for what I needed so I decided to make the 2 list views.
The jQuery I had when it worked for my select and option tags was as follows:
$("select#company").change(function(){
var id = $("select#company option:selected").attr('value');
$.post("select_site.php", {id:id}, function(data){
$("select#sites").html(data);
});
});
I won't lie, jQuery is not my biggest strength and I can't for the life of me work out why it won't populate the second list. absolutely any help would be really really appreciated as I have spent the last 3 days trying to figure this out. Thank you.

Categories