Delete index session in PHP - php

I have question referring to the session in PHP.
I've coded in PHP for setting the session and I want to delete it , but I got some errors and confusing with using the UNSET(variable $_SESSION). Perhaps anyone could help me to show what should I do with this matter. Thanks in advance
$_SESSION['chart'] = array();
$_SESSION['chart'][0]['index'] = 0
$_SESSION['chart'][0]['type'] = $type;
$_SESSION['chart'][0]['idanimal'] = $iddog;
$_SESSION['chart'][0]['price'] = $price;
printdata(); // <== this is the function to print out the data
All I want to do is just delete based on the index in this session
Here's the function :
function printdata()
{
$totalharga = 0;
if(is_array($_SESSION['chart']))
{
echo "<h3>"."Berikut adalah keranjang belanja anda" . "</h3>". "<br>";
$max = count($_SESSION['chart']);
$th1 = "<th>" . "No" . "</th>";
$th2 = "<th>" . "Animal Type" . "</th>";
$th3 = "<th>" . "ID Binatang" . "</th>";
$th4 = "<th>" . "Harga" . "</th>";
$th5 = "<th>" . "Hapus Data" . "</th>";
echo "<table border=1>";
echo "<tr>";
echo $th1 ;
echo $th2;
echo $th3;
echo $th4;
echo $th5;
echo "</tr>";
for ($indexo = 0; $indexo < $max; $indexo++)
{
echo "<tr>";
echo "<td>" . $indexo."</td>";
echo "<td>" . $_SESSION['chart'][$indexo]['type']."</td>";
echo "<td>" . $_SESSION['chart'][$indexo]['idanimal']."</td>";
echo "<td>" . "Rp. " . $_SESSION['chart'][$indexo]['harga']. ",-" ."</td>";
echo "<td>" . "<a href='deletesession.php?session=$indexo'>" ."Proses ". "</a>"."</td>";
$totalharga += $_SESSION['chart'][$indexo]['harga'];
echo "</tr>";
}
echo "</table>" . "<br/>";
echo "<blockquote>" . "Total Pembelian Item Yang Anda Pesan =". "<h2>". "Rp." . $totalharga . ",-" ."</h2>" . "</blockquote>";
}else
{
echo "Chart is still Empty";
}
}
I've already tried this :
Suppose that there is a chart already filled by the contents then I tried to delete within this code, I've received error with the unset variable
unset($_SESSION['chart'][1])
Thank you

I spot several things that could be improved in your code:
Don't echo in your functions, return instead (then echo what the function returns). This gives you more flexibility regarding what you do with your result.
PHP has a built-in loop for iterating arrays, the foreach loop. You should be using that instead of for.
So here's what I have:
function print_session_data($session) {
if (!is_array($session)) {
return "Array is empty";
}
$table_data = "";
$total_harga = 0;
foreach ($session as $index => $data) {
$table_data .= <<<TABLE_DATA
<tr>
<td>$index</td>
<td>{$data["type"]}</td>
<td>{$data["idanimal"]}</td>
<td>Rp. {$data["harga"]}</td>
<td>Proses</td>
</tr>
TABLE_DATA;
$total_harga += $data["harga"];
}
$result = <<<RESULT
<h3>Berikut abalah keranjang belanja anda</h3>
<table border="1">
<thead>
<tr>
<th>No</th>
<th>Animal Type</th>
<th>ID Binatang</th>
<th>Harga</th>
<th>Hapus Data</th>
</tr>
</thead>
<tbody>
$table_data
</tbody>
</table>
<blockquote>Total Pembelian Item Yang Anda Pesan = <strong>Rp. $total_harga</strong></blockquote>
RESULT;
return $result;
}
$_SESSION['chart'] = array();
$_SESSION['chart'][0]['type'] = "Type";
$_SESSION['chart'][0]['idanimal'] = 6;
$_SESSION['chart'][0]['price'] = '$25';
$_SESSION['chart'][0]['harga'] = 25;
echo print_session_data($_SESSION["chart"]); // <== this is the function to print out the data

Suppose that there is a chart already filled by the contents then I
tried to delete within this code, I've received error with the unset
variable unset($_SESSION['chart'][1])
From what I can see from your code the best way to unset the data correctly is as follow:
DEMO.
You have to check if the $_SESSION['chart'][0] was set before using the session variable index again. If it $_SESSION['chart'] array still contains other indexes then you can call printdata(); else indicate that the session was empty.

Related

Array: Compare values from API with values from own database

I have built a list (moviesSeen) where people can save their seen movies.
Now I want to get the director for each movie from an API and then compare which movies have already been seen. The output of the movies works without problems, but I can't get the result from the database (moviesSeen) to match the movies of the director. How can I achieve this?
The goal of the script is to show all movies of a director and mark all the ones you have already seen.
function getCrewDetails() {
global $apiKey;
global $language;
$personID = htmlspecialchars($_GET['personID']);
$url = "https://api.themoviedb.org/3/person/" . $personID . "?api_key=" . $apiKey . "&" . $language . "";// path to your JSON file
$data = file_get_contents($url); // put the contents of the file into a variable
$personPrivate = json_decode($data); // decode the JSON feed
echo '<div class="row">';
echo '<div class="col">';
echo '<img src="https://image.tmdb.org/t/p/w300/' . $personPrivate->profile_path . '" class="img-thumbnail">';
echo '</div>'; // end div col
echo '<div class="col-8">';
echo '<h1>' . $personPrivate->name . '</h1>';
if (!empty($personPrivate->biography)) {
echo $personPrivate->biography;
} else {
echo '<p>Verdammmt! Zu dieser Person liegen keine biographischen Details vor.</p>';
echo '<p>Dabei hätte sie es doch so verdient :(</p>';
}
echo '</div>'; // end div col
echo '</div>'; // end div row
// echo '<pre>';
// print_r($person);
$url = "https://api.themoviedb.org/3/person/" . $personID . "/movie_credits?api_key=" . $apiKey . "&" . $language . "";// path to your JSON file
$data = file_get_contents($url); // put the contents of the file into a variable
$personCareer = json_decode($data); // decode the JSON feed
echo '<div class="container mt-4">';
echo "<h2>Filmographie</h2>";
echo '<table class="table table-striped table-sm">';
echo '<thead>';
echo '<tr>';
echo '<th scope="col">Film</th>';
echo '<th scope="col">Gesehen</th>';
echo '<th scope="col">Funktion</th>';
echo '</tr>';
echo '</thead>';
echo '<tbody>';
global $pdo;
$stmt = $pdo->prepare("SELECT * FROM movieSeen WHERE user_id = '" . $_SESSION['id'] . "'");
$stmt->execute();
foreach ($stmt as $row ) {
echo $row['movie_id'] . ', ';
} // output of the saved IDs in movieSeen
foreach ($personCareer->crew as $showCrewDetails) { //Output of the movies
echo '<tr>';
echo '<td>' . $showCrewDetails->title . ' ' . $showCrewDetails->id . ' (' . substr($showCrewDetails->release_date, 0, 4) . ')</td>';
echo '<td><span class="badge badge-danger">Movie Seen</span></td>';
echo '<td>' . $showCrewDetails->job . '</td>';
echo '</tr>';
}
echo '</tbody>';
echo '</table>';
echo '</div>';
//echo '<pre>';
//var_dump($personCareer);
}
I know that I have to edit the last foreach loop, but I just can't get it to work :(

I want to display subject for specific class i.e A or B but current I display only A?

I try to display every each data on the specific td, but I dont know where to fix my code. Please check the screenshop below to understand the clearly problems. Please any help to solve this problems.
<table class="table table-hover table-bordered ">
<tr><th>Day</th><th colspan="2">08:00-08:40</th><th colspan="2">8:40-09:20</th><th colspan="2">09:20-10:00</th><th>10:00-10:15</th><th colspan="2">10:15-10:55</th><th colspan="2">10:55-11:35</th><th colspan="2">11:35-12:15</th><th>12:15-01:15</th><th colspan="2">01:15-01:55</th><th colspan="2">01:55-02:35</th></tr>
<?php
$timesVariants = array("08:00-08:40", "08:40-09:20", "09:20-10:00", "10:00-10:15", "10:15-10:55", "10:55-11:35", "11:35-12:15", "12:15-01:15", "01:15-01:55","01:55-02:35");
$sqlquery = "SELECT * FROM timetable,classroom,subprogramme WHERE classroom.classid = timetable.classid AND subprogramme.subid = timetable.subid";
$res = $connect->query($sqlquery);
$classes = array();
while($row = $res->fetch_assoc()) {
$classes[$row['day']][$row['tid']][$row['time']] = array('courseid'=> $row['cid'], 'classname' => $row['classname'], 'subname' => $row['subname']);
}
//This is a loop
foreach($classes as $day => $daySchedule) {
foreach($daySchedule as $teacher) {
print '<tr>';
print "<td>$day</td>";
foreach($timesVariants as $time) {
if (empty($teacher[$time])){
print "<td>*</td><td>*</td>";
}
else{
print '<td>' . $teacher[$time]['courseid'] . '</td><td>' . $teacher[$time]['subname'] . ''. $teacher[$time]['classname'] . '</td>';
}
}
print '</tr>';
}
}
?>
</table>
Output
Results display on the webpage
You trouble is in the GROUP BY. MySql have no strict restrictions (by default) that each column should use aggregation function, so the result is the first row, instead of complicating SQL use PHP, your result seems not to be huge, so another loop will not affect performance:
$timesVariants = array("08:00-08:40", "08:40-09:20", "09:20-10:00", "10:00-10:15", "10:15-10:55", "10:55-11:35", "11:35-12:15", "12:15-1:15", "01:15-01:55","01:55-02:35");
$sqlquery = "SELECT * FROM timetable";
$classes = array();
while($row = $res->fetch_assoc()) {
$classes[$row['day']][$row['tid']][$row['time']] = array('subject'=> $row['subject'], 'class' => $row['class'], 'progid' => $row['progid']);
}
//This is a loop
foreach($classes as $day => $daySchedule) {
foreach($daySchedule as $teacher) {
print '<tr>';
print "<td>$day</td>";
foreach($timesVariants as $time) {
if (empty($teacher[$time]))
print "<td>None</td><td>None</td>";
else
print '<td>' . $teacher[$time]['subject'] . '</td><td>' . $teacher[$time]['class'] . '</td>';
}
print '</tr>';
}
}
<?php
if(isset($_POST["tid"])){
$tid = $connect->real_escape_string($_POST["tid"]);
$sqlquery = "SELECT * FROM timetable,classroom,subprogramme WHERE classroom.classid = timetable.classid AND subprogramme.subid = timetable.subid AND timetable.tid = ".$tid." ORDER BY timetable.timid ASC";
$res = $connect->query($sqlquery);
if($res->num_rows > 0){
?>
<table class="table table-bordered table-striped">
<tr><th>Day</th><th colspan="2">8:00-8:40</th><th colspan="2">8:40-9:20</th><th colspan="2">9:20-10:00</th><th colspan="2">10:00-10:15</th><th colspan="2">10:15-10:55</th><th colspan="2">10:55-11:35</th><th colspan="2">11:35-12:15</th><th colspan="2">12:15-1:15</th><th colspan="2">1:15-1:55</th><th colspan="2">1:55-2:35</th></tr>
<?php
$timesVariants = array("8:00-8:40", "8:40-9:20", "9:20-10:00", "10:00-10:15", "10:15-10:55", "10:55-11:35", "11:35-12:15", "12:15-01:15", "1:15-1:55","1:55-2:35");
$classes = array();
while($row = $res->fetch_assoc()) {
$classes[$row['day']][$row['tid']][$row['time']] = array('courseid'=> $row['cid'], 'classname' => $row['classname'], 'subname' => $row['subname']);
}
//This is a loop
foreach($classes as $day => $daySchedule) {
foreach($daySchedule as $teacher) {
print '<tr>';
print "<td>$day</td>";
foreach($timesVariants as $time) {
if (empty($teacher[$time])){
print "<td>*</td><td>*</td>";
}
else{
print '<td>' . $teacher[$time]['courseid'] . '</td><td>' . $teacher[$time]['subname'] . ''. $teacher[$time]['classname'] . '</td>';
}
}
print '</tr>';
}
}
?>
</table>
<?php
}
else{ print "<div class='alert alert-danger col-md-4'><span class='glyphicon glyphicon-remove'></span> Not yet set timetable</div>"; }
} ?>
</div>
The problems was on td I forgot to put colspan = 2, and other problem on sql query I forgot to inner join the tables in order to get all right that i want to display on the page.

PHP passing values from generated textboxes

I'm creating a PHP web application in combination with SQL to order stuff. I'm randomly generating textboxes based on the amount of records I have. I want to pass the individual values to insert to the database. I want each cell to have a textbox in which I can input values and pass them with that cell. So if I want to order 2 of cell one I want to pass that value into a database.
Here's the code:
$i = 0;
if ($AanbodsTabel === false){
die(mysql_error());
}
while ($row = mysqli_fetch_array($AanbodsTabel)){
echo "<tr><td width = 4%>". htmlentities($row['Fustcode']) . "</td>";
echo "<td width = 8%>" . htmlentities($row['cultivar']) . "</td>";
echo "<td width = 6%>" . htmlentities($row['AantalFust']) . "</td>";
echo "<td width = 6%>" . htmlentities($row['AantalPerFust']) . "</td>";
echo "<td width = 6%>" . htmlentities($row['AantalStelen']) . "</td>";
echo "<td width = 4%><input type ='text' id='Bestelbox' value='' name='AantalBestellen".$i."'></td>";
echo "<td width = 6%>" . htmlentities($row['AantalFustBesteld']) . "</td>";
echo "<td width = 6%>" . htmlentities($row['AantalStelenBesteld']) . "</td>";
135: echo '<td width = 8%><a href="Home.php?aanbodid='. htmlentities($row['aanbodid']) .'&hoeveelheid='. $_GET["AantalBestellen$i"]. '"'
. ' class = "btnBestel">Bestel</a></td></tr>';
$i = $i + 1;
}
The error I'm getting is undefined index. I guess this is because the name isn't unique. But whatever I do I still get the error.
I'm getting:
undefined index: AantalBestellen0 on line 135;
you can use javascript for example
note i will bold the code you need, the rest is context.
note this is from a similar project of mine but you should get the point.
<div id="meldingen_top_div">
<?php
echo "<div class='alert_Top_Div_Left_Outer'>
<input type='submit' value='Openstaande Meldingen' class='btnLoad' name='' onclick='toggleThis(" . '"' . "#meldTableTop" . '"' . "), toggleThis(".'"'.".alert_Top_Div_Left_Inner".'"'.")'/>
<div class='alert_Top_Div_Left_Inner'>
<table class='tableRed' id='meldTableTop'><caption/><thead/><tfoot/><tbody>";
$sqlVII = "SELECT Meldingen.Melding_id, FORMAT(Meldingen.Melding_datum, 'dd-mM-yyyy') AS Melding_datum, Producten.Product_naam, Leveranciers.Leverancier_naam, Meldingen.Melding_notitie
FROM MovieWorld.dbo.Producten,
MovieWorld.dbo.Meldingen,
MovieWorld.dbo.Categorieen,
MovieWorld.dbo.Leveranciers
WHERE Producten.Product_id = Meldingen.Product_id AND Producten.Categorie_id = Categorieen.Categorie_id AND Categorieen.Leverancier_id = Leveranciers.Leverancier_id AND Producten.Product_actief = 1 AND Meldingen.Melding_actief = 1
";
$resV= $db->executeQuery($sqlVII);
$i=1;
if($resV!=FALSE){
while($arrx = sqlsrv_fetch_array($resV)){
Code wich is relevant for you:
echo "<tr>
<td><p class='meldDate'>{$arrx['Melding_datum']}</p></td>
<td>{$arrx['Product_naam']}</td>
<td>{$arrx['Leverancier_naam']}</td>
<td><input id='txt{$i} type='text' name='thisdoesntevenmatter' value='..'/></td>
<td><img src='somerandompath.png' onclick='getTxt(".'"txt{$i}"'.")'/></td>
</tr>"
$i=$i+1;
}
}else{}echo '</tbody></table></div></div>';
?>
</div>
and the Javascript function
function getTxt(id){
var tempId = document.getElementById(id).value;
return tempId;
}
however.. you can also send the value back into a php variable, OR use AJAX to pass it to an PHP class to insert it into the Database.
edit
Your quotes in line 135: seem incorrect. try this:
echo '<td width = 8%><a href="Home.php?aanbodid={htmlentities($row['aanbodid']) }&hoeveelheid={$_GET['AantalBestellen$i']}"'
. ' class = "btnBestel">Bestel</a></td></tr>';
Where you get undefined index? on that $_POST['AantalBestellen'] ?
Use
if (isset($_POST['AantalBestellen'])) { }
to identify that the post value has been set
same do later for the hoeveelheid:
if (isset($_GET['hoeveelheid'])) { }
echo-ing the input field:
echo "<td width = 4%><input type ='text' id='Bestelbox' value='" . $_GET['hoeveelheid'] . "' name='AantalBestellen'></td>";
Also, dont forget to clear the spaces in:
'&hoeveelheid = '. $_POST //near the =

Amazon SQS Messages not deleting in PHP

I list the messages in my Amazon SQS queue and then have the option to delete them, one at a time. When I delete the message I get a SUCCESS message back. However, not a single message is deleted and they all return to the queue.
Here is the list queue code:
<?php
include_once("sdk.class.php");
// Instantiate
$sqs = new AmazonSQS();
$rows = $sqs->get_queue_size('https://sqs.us-east-1.amazonaws.com/199992002821/SomeQueueSQS');
echo "<table>";
echo "<tr>";
echo "<td width=20 valign=top bgcolor=" . $adHeading . " align=left><strong>No</strong></td>";
echo "<td width=200 valign=top bgcolor=" . $adHeading . " align=left><strong>Message</strong></td>";
echo "<td width=50 align='right' bgcolor=" . $adHeading . "><a href='sqs.php'><img src='images/icon_refresh.png' border='0'></a></td>";
echo "</tr>";
for ($j = 0; $j < $rows; ++$j)
{
// Get Message
$response = $sqs->receive_message('https://sqs.us-east-1.amazonaws.com/199992002821/SomeQueueSQS', array(
'VisibilityTimeout' => 30
));
$body = $response->body->ReceiveMessageResult->Message[0]->Body;
$rcpt_hand=($response->body->ReceiveMessageResult->Message[0]->ReceiptHandle);
$id = $j + 1;
echo "<tr>";
echo "<td valign=top bgcolor=" . $bgcolor . ">$id</td>";
echo "<td valign=top bgcolor=" . $bgcolor . ">$body</td>";
echo "<td valign=top><a href=sqsdelete.php?sid=$rcpt_hand><img src=images/icon_delete.gif border=0 width=18 height=18></a></td>";
echo "</tr>";
}
echo "</table>";
?>
Here is the delete code:
<?php
if ($response = $sqs->delete_message('https://sqs.us-east-1.amazonaws.com/199992002821/SomeQueueSQS', $rcpt_hand)) {
echo "Message deleted<br>";
} else {
echo "Message not deleted<br>";
}
// Get list of unprocessed and valid messages
$rows = $sqs->get_queue_size('https://sqs.us-east-1.amazonaws.com/199992002821/SomeQueueSQS');
echo "<table>";
etc...
Thanks
Andre
The if() condition in your delete code is wrong. Your condition will always return true.
You need to make the request, then check if $response->isOK() is true or false. If the request was completed successfully, AWS will return a 2xx status code, and the isOK() method will return true.
If you make that change and start seeing failures, use print_r($response->body) to view the error message that SQS is sending back. That should help you debug.

AJAX add data to table without resetting table.

I have a php page that will grab data from an SQL database and print it into a table, now if certain rows from the database have a certain parameter, a hidden row is inserted below that with a button to expand the row. This all works fine and I can query it with ajax into a div on a different page, but if someone were to expand the hidden row (with jquery) and the ajax update timer were to come along, it would reset and hide that row.
Here is the page that it is filled into and the ajax code to go with it:
<script type="text/javascript">
$(document).ready(function() {
$("#query").load("query.php");
var refreshId = setInterval(function() {
$("#query").load('query.php');
}, 5000);
$.ajaxSetup({ cache: false });
});
</script>
<div id="query"></div>
And from the query.php:
while($row = mysql_fetch_array($result))
{
$decoded = json_decode($row['B'],true);
$r = $decoded['r'];
$t = $decoded['t'];
$l = $decoded['l'];
$g = $decoded['g'];
$tp = (int)$t + 3;
echo "<tr>";
echo "<td>" . $row['ID'] . "</td>";
echo "<td align=\"center\"><font color=\"red\">[$t]</font></td>";
echo "<td align=\"center\"><font color=\"blue\">[$r]</font></td>";
echo(((int)$t != 0) ? '<td><button class="expand stylebutton">+</button>' : '<td>');
echo $row['Name_'] . "</td>";
echo "<td>" . $row['Date_'] . "</td>";
echo "<td>" . $row['IP'] . "</td>";
echo "<td>" . $row['G'] . "</td>";
echo "<td>" . $row['A'] . "</td>";
echo "<td>" . $row['Add'] . "</td>";
echo "<td>" . $row['Remove'] . "</td>";
echo "<td>" . $row['Comments'] . "</td>";
echo "</tr>";
if((int)$t != 0)
{
echo "<tr class=\"b\"style=\"display: none;\">";
echo "<td></td><td colspan=\"$tp\"><div style=\"color: #FC0;\"> Local:</div>";
foreach($l as $ll)
{
echo $ll . "<br>";
}
echo "<br><div style=\"color: #F00;\">Global:</div>";
foreach($g as $gg)
{
echo $gg . "<br> ";
}
echo "</td></tr>";
}
}
echo "</table>";
echo "<script type=\"text/javascript\">";
echo "$(document).ready(function() {
$(\".stylebutton\").click(function(){
$(this).parent().parent().next().toggle();
if($(this).text() == \"+\")
{
$(this).text('-');
}
else
{
$(this).text('+');
}
});
});
</script>";
Here's an image of what one of the rows looks like when expanded.
So basically I don't want the rows to contract when the ajax update rolls through, but instead just add more data on to the page. Thanks for any help!
You should have the php file return the data in json format to be used by your jQuery. Instead of replacing the html tags and causing your UI to retract, you will replace the data.
For Example
Your php code:
$data_array = array();
while($row = mysql_fetch_array($sql)) {
array_push( $row['some_row'] , $data_array ); // add the data to an array that will later be json encoded
}
echo json_encode($data_array);
jQuery
$.ajax({
url: 'query.php',
success: function(data) {
alert('This is the JSON: ' + JSON.stringify(data));
$('#selector').text(data.some_row); // place the data inside the element with id = 'selector'
}
});

Categories