Remove selected items from $_POST / $_SESSION array - php

I am posting from a form that selects products from a list, to a page with the selected products displayed. I want to have a link next to each item for removing an item from the selected list (array).
How do I do that? I seem to be losing the session once I click on the remove link.
session_start();
foreach($_SESSION['id'] as $key => $value){
$array = explode(',', $value);
if($value[0]!=''){
$id = $array[0];
$query = "SELECT * FROM products WHERE id = '$id'";
$result = mysqli_query($dbc, $query);
while ($row = mysqli_fetch_array($result)) {
$product_id = $row['id'];
echo '<tr valign="bottom">';
echo '<td>' . stripslashes($row['category']) . '</a></td>';
echo '<td>' . stripslashes($row['itemDesc']) . '</a></td>';
echo '<td class="right">' . stripslashes(number_format($row['points'], 2)) . '</a></td>';
echo '<td>Remove</td>';
echo "</tr>\n\n";
$points = stripslashes($row['points']);
#$points_total += $points;
}
}
}
$postid = $_POST['id'];
$_SESSION['id'] = $_POST['id'];
$product_id = htmlspecialchars(#$_GET['id'], ENT_QUOTES, 'UTF-8');//the product id from the URL
$s = $_SESSION['id'];
$s = htmlspecialchars(#$_GET['key'], ENT_QUOTES, 'UTF-8');//the product id from the URL
$action = htmlspecialchars(#$_GET['action'], ENT_QUOTES, 'UTF-8'); //the action from the URL
switch($action) {
case "remove":
unset($array[$id]); //remove $product_id from the array with
echo $action . $product_id;
break;
}
Here's the HTML for the form:
<form method="post" action="products_selected.php">
<?php
$query = "SELECT * FROM products ORDER BY rangeCode, category ASC";
$result = mysqli_query($dbc, $query);
while ($row = mysqli_fetch_array($result)) {
$id = $row['id'];
echo '<tr valign="bottom">';
echo '<td>' . stripslashes($row['rangeCode']) . '</td>';
echo '<td>' . stripslashes($row['category']) . '</a></td>';
echo '<td>' . stripslashes($row['itemDesc']) . '</a></td>';
echo '<td>' . number_format($row['points'], 2) . ' points ';
echo '<input type="checkbox" name="id[]" value="' . $id . '" /></td>';
echo '</tr>' . "\n\n";
}
mysqli_close($dbc);
?>
<tr><td colspan=13><input type="submit" name="submit" value="Order" /></td></tr>

Ok. After a bit of chat and co-working around this issue, we found some problems.
There's the need to insert a check around the code that uses $_GET and $_POST data, to avoid unwanted modification to other variables (an example: when the user clicks "Remove" to remove an item from his choices, the $_SESSION array will be updated with the $_POST array; since this contains nothing, the session array is emptied (and this was why the session was thought to be lost):
To find and delete the item from the session, we have to use the key retrieved from url and check if it's present into the session array. This can be seen in the code below.
if (isset($_POST['id']))
{
$_SESSION['id'] = $_POST['id'];
}
if(isset($_GET['key']) && ($_GET['action'] == 'remove'))
{
if (array_key_exists($_GET['key'], $_SESSION['id']))
{
unset($_SESSION['id'][$_GET['key']]);
}
}
Some other minor changes have been made to the code, but the main problems were the ones explained.

Related

Buttons created using a PHP while loop are not updating the MySQL database

I am creating a multiuser shared to do list application using PHP and MySQL. Currently, my application is displaying the to do list items by iterating over the database table with a while loop.
All of that works correctly, so I know I am connecting to the database. Part of the while loop also generates buttons that allow a user to "claim" an item that does not have anyone working on it or to indicate that at item has been completed. However, the buttons are not updating the database table.
<?php
include 'includes/dbh.inc.php';
$sql = 'SELECT * FROM items WHERE item_is_done = 0';
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_assoc($result)) {
$creator = $row['item_creator'];
$owner = $row['item_owner'];
$id = $row['item_id'];
if (isset($_POST['do_item'])) {
$update = "UPDATE items SET item_owner = $currentID WHERE item_id = $id;";
mysqli_query($conn, $update);
header("Location: ../todo.php?code=doing");
exit();
} else if(isset($_POST['complete_item'])) {
$update = "UPDATE items SET item_is_done = 1 WHERE item_id = $id;";
mysqli_query($conn, $update);
header("Location: ../todo.php?code=done");
exit();
}
echo '<h4>Item ID:</h4>' . $id . '<br><br>';
echo '<h4>Item created by:</h4>' . $creator . '<br><br>';
echo '<h4>Date Added: </h4>' . $row['item_add_date'] . '<br><br>';
echo '<h4>Item Title: </h4>' . $row['item_title'] . '<br><br>';
echo '<h4>Description: </h4>' . $row['item_description'] . '<br>';
if($row['item_owner'] == 'None') {
echo '<br>';
echo '<button type="submit" name="do_item" formaction="todo.php" formmethod="POST">Do Item</button>';
echo '<br>';
} else if($row['item_owner'] != 'None') {
echo '<br>';
echo '<h4>Item is being worked on by: </h4>' . $owner . '<br><br>';
echo '<button type="submit" name="complete_item" formaction="todo.php" formmethod="POST">Complete Item</button>';
echo '<br>';
}
echo '<hr>';
}
?>
I was also got stuck on same kind of problem what I did was I tried to put the updating variables in ' ' single quotes.
If it can help you you can try this queries
$update = "UPDATE items SET item_owner='$currentID' WHERE item_id='$id'";
$update = "UPDATE items SET item_is_done='1' WHERE item_id ='$id'";

Passing array by radio button

So in this part of the website i'm making an edit person information page and if there are more than one person with the name searched you get a table with all the persons; you choose the needed one and edit it in another page.
I need to pass the array that matches with the person selected. I don't know how to pick the array in the other page through POST. This is a part of code of the page that sends the array:
$squery=mysqli_query($conn,"SELECT * FROM amico WHERE (Nome= '" .
$nome . "') AND (Cognome ='" .$cognome. "')");
$num = mysqli_num_rows($squery);
$i=0;
$array= array();
while($rowa=mysqli_fetch_assoc($squery)){
$array[$i]=$rowa;
$i++;
}
$ssquery=mysqli_query($conn,"SELECT * FROM amico WHERE (Nome= '" .
$nome . "') AND (Cognome ='" .$cognome. "')");
if($num > 1) {
echo 'Trovato più di un elemento';
echo '<table border="1">';
echo '<tr>';
echo '<td><p>S</p></td>';
echo '<td><p>Nome</p></td>';
echo '<td><p>Cognome</p></td>';
echo '<td><p>Citt&agrave</p></td>';
echo '</tr>';
$i=0;
echo '<form method="POST" action="moficatr.php">';
while ($row = mysqli_fetch_array($ssquery)) {
echo '<tr>';
echo '<td> <p> <input type="Radio" name="persona" value="'.
$rowa[$i] . '"></p></td>';
echo ' <td><p>' .$row['Nome'] . '</p></td>';
echo '<td><p>'.$row['Cognome'].'</p></td>';
echo '<td><p>'.$row['Citta'].'</p></td>';
echo '</tr>';
$i++;
}
echo '</table>';
echo '<br><br><input type="submit" value="Modifica"></form>';
}
You can simply pass the selected user's ID to the next page and then fetch all the details using the ID from that page instead of sending the whole array of data to the other side.
Why are you executing the same query twice in your code ? you only need one query which will give you all the data.
Also I strongly encourage you to use PDO please - http://php.net/manual/en/book.pdo.php Or at least prepared statments which is supported in MySQLi as well
$ssquery=mysqli_query($conn,"SELECT * FROM amico WHERE (Nome= '" .
$nome . "') AND (Cognome ='" .$cognome. "')");
$num = mysqli_num_rows($ssquery);
if($num > 1) {
echo 'Trovato più di un elemento';
echo '<table border="1">';
echo '<tr>';
echo '<td><p>S</p></td>';
echo '<td><p>Nome</p></td>';
echo '<td><p>Cognome</p></td>';
echo '<td><p>Citt&agrave</p></td>';
echo '</tr>';
echo '<form method="POST" action="moficatr.php">';
while ($row = mysqli_fetch_assoc($ssquery)) {
echo '<tr>';
echo '<td> <p> <input type="Radio" name="persona" value="'.
$row['id'] . '"></p></td>'; //you can change 'id' with your column name if it's different
echo ' <td><p>' .$row['Nome'] . '</p></td>';
echo '<td><p>'.$row['Cognome'].'</p></td>';
echo '<td><p>'.$row['Citta'].'</p></td>';
echo '</tr>';
$i++;
}
moficatr.php
//Set up a Mysql connection.
$user_id = (int) $_POST['persona'];
//Query the db to fetch all the details of this user.
$query = "SELECT * from your_table where id=?";
//Prepare statment and execute.
$stmt = mysqli_prepare($connection, $query);
mysqli_stmt_bind_param($stmt, "i", $user_id);
mysqli_stmt_execute($stmt);
/* bind result variables */
mysqli_stmt_bind_result($stmt, $name, $address,...);
echo $name;
echo $address;

SESSIONS not transferring information php5.5

I have recently changed servers and things arent working like they did before
I have pin pointed that the session information is not tranferring from one page to the next
this is half of the first page
<?php include 'header.php';?>
<?php
session_start();
$id = isset($_GET['id']) ? $_GET['id'] : "";
$con = mysqli_connect("*","*","*","*");
// SELECT DATABASE
$db = mysqli_select_db("images", $con);
function GetCartId()
{
// This function will generate an encrypted string and
// will set it as a cookie using set_cookie. This will
// also be used as the cookieId field in the cart table
if(isset($_COOKIE["cartId"]))
{
return $_COOKIE["cartId"];
}
else
{
// There is no cookie set. We will set the cookie
// and return the value of the users session ID
setcookie("cartId", session_id(), time() + ((3600 * 24) * 30));
return session_id();
}
}
// Get data from the database depending on the value of the id in the URL
$id = $_GET["id"];
$strSQL = "SELECT * FROM images WHERE image= '$id'";
$rs = mysqli_query($con,$strSQL);
while($row = mysqli_fetch_array($rs)) {
$name = $row['image_name'];
echo '<h1 style="font-size:2em;">';
echo $name;
echo'</h1>';
echo '<div id = "galpic">';
$thispic = $row['image'];
echo '<div id = "pic">';
echo '<br /> <img src="'.$thispic.'" style = "max-width:100%;"/> ';
echo '</div>';
$description = $row['image_description'];
echo ' <h3>about</h3>';
echo ' <h3>card</h3>';
echo ' <h3>small</h3>';
echo ' <h3>big</h3>';
echo ' <h3>limited</h3>';
echo ' <h3>share</h3>';
echo '</div>';
}
$_SESSION['name'] = $name;
$_SESSION['thispic'] = $thispic;
THESE LAST TWO LINES ARE THE SESSION INFORMATION THAT WORKS FOR THE REST OF THIS PAGE BUT DOES NOT PASS THROUGH TO THE NEXT PAGE
then the next page is............
<?php include 'header.php';?>
<?PHP
session_start();
$con = mysqli_connect("*","*","*","*");
$_SESSION['name'] = '$name';
$_SESSION['thispic'] = '$thispic';
echo '<div id = "foodbowl">';
echo '<h1>ORDER FORM</h1>';
echo '</div>';
echo '<div id = "checkout">';
echo '<table style = "font-size:0.7em;margin-top:3%;line-height:100%;">';
echo '<tr>';
echo '<td>checkout progress bar:</td>';
echo '<td>check your order</td>';
echo '<td style = "background-color:#e8d9d9">fill in details</td>';
echo '<td>choose payment option</td>';
echo '<td>final check?</td>';
echo '</tr>';
echo '</table>';
echo '</div>';
function GetCartId()
{
// This function will generate an encrypted string and
// will set it as a cookie using set_cookie. This will
// also be used as the cookieId field in the cart table
if(isset($_COOKIE["cartId"]))
{
return $_COOKIE["cartId"];
}
else
{
// There is no cookie set. We will set the cookie
// and return the value of the users session ID
setcookie("cartId", session_id(), time() + ((3600 * 24) * 30));
return session_id();
}
}
$checkout = mysqli_query($con,"SELECT * FROM cart where cookieId = '".GetCartId()."'");
echo '<div id = "checkout">';
echo '<table>
<tr>
<th colspan = "4"><b>YOUR CHOICE</b></th>
<th><b>PRICE</b></th>
</tr>
';
while ($row = mysqli_fetch_array($checkout)){
$pic = $row['image'];
echo '<tr><td>';
echo $row['name'];
echo '</td><td>';
echo '<img src="'.$pic.'" style ="height:33px;"/>' ;
echo '</td><td >';
echo $row['product'];
echo '</td><td >';
echo '$'. $row['price'].'.00 au';
echo '</td></tr>';
}
echo '<tr><td colspan ="4">';
echo '<p>TOTAL</P>';
echo '</td><td>';
$result = mysqli_query($con,"select sum(price) as total from cart where cookieId = '".GetCartId()."'");
while($row = mysqli_fetch_assoc($result)){
echo '$'.$row['total'].'.00 au';
}
echo '</td></tr>';
echo '</table>';
echo '</div>';
$name = $row['name'];
$product = $row['product'];
?>
<form id="buyer" method="post" action="email.php" >
<p> these are the details Mandy will need to send your product -</p>
<?php
$checkout = mysqli_query($con,"SELECT * FROM cart where cookieId = '".GetCartId()."'");
while ($row = mysqli_fetch_array($checkout)){
echo '<br / >';
echo 'a '.$row['product'];
echo ' of '.$row['name'];
}
?>
You cannot have any - any - output before you call session_start(). That includes the blank line between ?> and <?php, as well as anything in header.php. When you do have output, it prevents you from sending a session cookie with session_start(). No cookie, no session.
Put session_start() at the very top of your scripts and don't open and close PHP tags (<?php ... ?>) without reason.

PHP and select in loop

I have a PHP page where its querying data from the database and putting it in a table. The first column is where I would like the user to assign a person to that row. I was able to do that successfully (the select in a loop) but now I'm having a problem when its getting pushed out to the other page.
Below is the first page:
$sql = "SELECT * FROM meetingDump WHERE Meeting_ID IN ($Series)";
$rs=odbc_exec($conn,$sql);
while($row = odbc_fetch_array($rs))
{
$ID = odbc_result($rs,"ID");
$Meeting_ID = odbc_result($rs,"Meeting_ID");
$Title = odbc_result($rs,"Title");
$StartTime = odbc_result($rs,"StartTime");
$EndTime = odbc_result($rs,"EndTime");
$Organizer = odbc_result($rs,"Organizer");
echo '<tr>
<td>';
{
$box1 = array();
$result1 = "SELECT FullName FROM User";
$rs1=odbc_exec($connu,$result1);
while($row = odbc_fetch_array($rs1)) { $box1[] = $row; }
}
/* Generate select box contents */
$AssignedTo = '<select name="AssignedTo[]" onchange="autoSubmit()">';
$AssignedTo .= '<option selected="selected">---< Select Engineer >---</option>';
if (!empty($box1)) {
foreach ($box1 as $k => $v) {
$AssignedTo .= '<option value="'.$v['FullName'].'">'.$v['FullName'].'</option>';
}
}
$AssignedTo .= '</select>';
/* Output */
echo $AssignedTo;
echo '
</td>
<input name="AssignedID[]" type="hidden" value="' . $ID . '" />
<td>' . $Meeting_ID . '</td>
<td>' . $Title . '</td>
<td>' . $StartTime . '</td>
<td>' . $EndTime . '</td>
<td>' . $Organizer . '</td>';
}
Now for the second page I currently have:
foreach($_POST['AssignedTo'] as $AssignedTo)
{
echo '<br>' . $AssignedTo;
}
That gets me all the selected names, which is perfect, but I'm trying to correlate the assignedTo field with the meeting_id field.
Any ideas?
UPDATE:
The comment from AeroX helped me figure it out!
$AssignedID = $_POST['AssignedID'];
$AssignedTo = $_POST['AssignedTo'];
foreach ($AssignedID as $Key => $value)
{
echo $AssignedID[$Key] .' '. $AssignedTo[$Key];
echo '<br>';
}
In your example, because of the way the POST variables $_POST['AssignedID'] and $_POST['AssignedTo'] will be populated you can just pull the Value from each Array where they both have matching Keys. This will then give you the related records.
Something like the below should work for you:
$AssignedID = $_POST['AssignedID'];
$AssignedTo = $_POST['AssignedTo'];
foreach(array_keys($AssignedID) as $Key)
{
echo $AssignedID[$Key];
echo $AssignedTo[$Key];
}

PHP $_SESSION only store the last variable

Thank you for reading this, I am building a shopping cart with PHP session, when I click the submit button on the form, the $_POST was able to pass the value to the $_SESSION[''] array, but when I click the submit button again, the $_SESSION array only contain my last $_POST variable and the previous variables are all gone. As a shopping cart, the session array suppose to contain every data obtain from the POST value.
I checked with the SESSION_ID, which was able to shows the same ID when I submit the form, the var_dump shows the current SESSION array works (except only showing the last item). Please help me what is wrong in my code in order to keep the value into the SESSION array, thank you.
here is the full code, the sqli_query was replaced to specify item_id for troubleshooting, also this php will be included in another php that have an id in url, which seems irrelevant to this matter, but just for your information.
<?php if(!isset($_SESSION)){session_start();}?>
<?php
//if(isset($_GET['id']) && !empty($_GET['id'])){
require 'connecttosql.php';
$result = mysqli_query($con,"select COLOUR_EN, COLOUR_ZH, SIZE FROM mydb.item join mydb.colour using(item_id) join mydb.size using(item_id) WHERE ITEM_ID='T76'")
or die("Error: " . mysqli_error($con));
while($row = mysqli_fetch_array($result)){
$size[] = $row['SIZE'];
$colour_zh[] = $row['COLOUR_ZH'];
$colour_en[] = $row['COLOUR_EN'];
}
mysqli_free_result($result);
mysqli_close($con);
for($x=0;$x<count($colour_zh);$x++){
$colour[$x] = $colour_zh[$x] . "/" . $colour_en[$x];
}
echo "<form action='' method='POST'>";
echo "<ul>";
echo "<li>size: </li>";
echo "<li><select name = 'size'>";
foreach(array_unique($size) as $sizeli){
echo "<option value = '" . $sizeli . "'>" . $sizeli . "</option>";
}
echo "</select></li>";
echo "<li>colour: </li>";
echo "<li><select name = 'colour'>";
foreach(array_unique($colour) as $COLOURli){
echo "<option value = '" . $COLOURli . "'>" . $COLOURli . "</option>";
}
echo "</select></li>";
echo "<li><input type='SUBMIT' name='submit' value='ADDTOCART'></li>";
echo "</ul>";
$_SESSION['size'] = array();
$_SESSION['colour'] = array();
if(isset($_POST['submit'])) {
$_SESSION['size'][] = $_POST['size'];
$_SESSION['colour'][] = $_POST['colour'];
// $_SESSION['id'] = $_GET['id'];
}
echo SESSION_ID();
var_dump($_SESSION['size']);
var_dump($_SESSION['colour']);
// var_dump($_SESSION['id']);
/*
}else{
include 'index.php';
die();
}
*/
?>
You reinitialize (and therefore reset) the arrays at every request:
$_SESSION['size'] = array();
$_SESSION['colour'] = array();
Add a check like this:
if(!isset($_SESSION['size'])) {
$_SESSION['size'] = array();
}
if(!isset($_SESSION['colour'])) {
$_SESSION['colour'] = array();
}
it looks like you are resetting your session variables before it gets to this line...
if(isset($_POST['submit'])) {
try checking for existance of these before resetting...
$_SESSION['size'] = array();
$_SESSION['colour'] = array();
While doing this:
$_SESSION['size'] = array();
$_SESSION['colour'] = array();
you are doing a reset to $_SESSION['size'] and $_SESSION['colour'].
You can replace it with:
if(empty($_SESSION['size'])) $_SESSION['size'] = array();
if(empty($_SESSION['colour'])) $_SESSION['colour'] = array();
or just delete these two entries.

Categories