Remove item from session array - php

I am having trouble removing an item from the itinerary/array upon clicking a 'Remove location' link.
The value of the location to be removed is passed into the 'remove_loc.php' file as its unique 'loc_id' and assigned to a new variable. Upon doing this I then try to use 'unset()' to delete it from the session array but it doesn't seem to be working.
The value of the location is definitely being passed through to the 'remove_loc.php' file ok as I have run an echo statement at other end to make sure, and am connecting ok to db etc, so I believe the error is in my remove_loc.php file.
Code for itinerary.php (where locations are displayed).Note 'Remove Location' href link:
<?php
session_start();
include ("includes/db.php");
include("functions/functions.php");
include("includes/head.html");
include("includes/search_box.html");
include("includes/left_sidebar.html");
//If user not already logged in then redirect to the login page
if (!isset($_SESSION['user_id'])){
load_page();
}//if
//Display contents of itinerary
if(!empty($_SESSION['itinerary'])){
//Retrieve details of each location in array from database
$query = "SELECT * FROM locations WHERE loc_id IN (";
foreach ($_SESSION['itinerary'] as $loc_id=>$value)
{$query.=$loc_id.',';}
$query = substr($query, 0, -1).')ORDER BY loc_id ASC';
$result = mysqli_query($db, $query);
echo'<form action="itinerary.php" method="POST"><table><tr><th colspan="5">Locations in your itinerary<br></br></th></tr><tr>';
//Display locations in array
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
$loc_id = $row['loc_id'];
echo"<tr><td>{$row['loc_name']}<br></br></td>
<td>{$row['loc_desc']}</td>
<td><a href=remove_loc.php?value=$loc_id>Remove location</a><br></br></td>
";
}//while
mysqli_close($db);
}//if
else {echo '<p>Your itinerary is empty.<br></br></p>';}
echo '<p>
<a href=submit.php?submit=$submission>Save itinerary</a><br></br>
Your details<br></br>
Logout<br></br>
</p>';
?>
Code for 'remove_loc.php' (for removing location from session array):
<?php
session_start();
include ("includes/db.php");
include("functions/functions.php");
include("includes/head.html");
include("includes/search_box.html");
include("includes/left_sidebar.html");
?>
<html>
<h1>REMOVE LOCATION</h1>
<br></br>
<?php
//If user not already logged in then redirect to the login page
if (!isset($_SESSION['user_id'])){
load_page();
}//if
//Assign ID of location which has been passed to new variable
if(isset($_GET['value']))
$loc_id = $_GET['value'];
//Remove location from sess array?
if(isset($_SESSION['itinerary'][$loc_id])) unset($_SESSION['itinerary'][$loc_id]);
echo 'Removal successful!';
print_r($_SESSION);
?>
</html>

Related

Question on redirection of pages using php

Code for page1.php-(Here named as index.php)
<?php
require_once "pdo.php";
session_start();
if(!(isset($_SESSION['email'])||isset($_SESSION['password']))
{
$url = "login.html";
}
?>
<html>
<head></head><body>
<?php
if ( isset($_SESSION['error']) ) {
echo '<p style="color:red">'.$_SESSION['error']."</p>\n";
unset($_SESSION['error']);
}
if ( isset($_SESSION['success']) ) {
echo '<p style="color:green">'.$_SESSION['success']."</p>\n";
unset($_SESSION['success']);
}
if (isset($_SESSION['name']))
echo('<table border="1">'."\n");
$stmt = $pdo->query("SELECT name, email, password, user_id FROM users");
while ( $row = $stmt->fetch(PDO::FETCH_ASSOC) ) {
echo "<tr><td>";
echo(htmlentities($row['name']));
echo("</td><td>");
echo(htmlentities($row['email']));
echo("</td><td>");
echo(htmlentities($row['password']));
echo("</td><td>");
echo('Edit / ');
echo('Delete');
echo("</td></tr>\n");
}
?>
</table>
<!--Add New-->
<!--Login-->
I have been given page1.php which is the first page when a user opens the application.
In page1.php, a link is given to login. This page redirects to login.php which requires us to login with genuine email and password.
After logging in, it returns to page1.php which has options like add new item to some database or delete/edit data in database and it also has an option of logout which then gives back the original page1.php in which we have been given the option of login.
The problem is if I do operations on database via another page (i.e. like page2.php) it is doable but I am not able to update page1.php after the login.php redirects to page1.php.
How do I work so that login.php page redirects to index.php with modified options? (which are operations on database.) Also how do I do this using href tags in html instead button operations?

How to store a value in a session?

I am displaying the user names as links on a php page like this which on clicking navigates on particular user home page:
$msql=$db->prepare("SELECT * from users where id=? order by id desc");
$msql->bind_param("i",$user_id);
$msql->execute();
$msql = $msql->get_result();
$msql = $msql->num_rows;
while($usercount=$msql->fetch_assoc())
{
$Email = $usercount['email'];
$FirstName = $usercount['first_name'];
$LastName = $usercount['last_name'];
?>
<strong><?php echo $FirstName.' '.$LastName;?></strong>
<?php
}
?>
And for the navigation to the user home page on clicking the link, I am using like this :
<?php
if(isset($_GET['navigate']) && $_GET['navigate'] == "true"){
$_SESSION['email'] = $Email;
header('location: nextpage.php');
}
?>
So my page looks like this as link
user1
user2
user3
.
.
.
usern
My issue is whenever I click on any of the links it always stores the first email in the session variable.
So, if I output the SESSION in nextpage.php
echo $_SESSION['email'];
it always echoes the first link email.
My guess for this because of the while loop I am using it always picks up the first link data and stays with it, but my question is how do i get the data for others as well. I want to navigate to that user page for which the link is clicked and that can only be done if I get the correct email on clicking the link.
As you said id is not primary key, and i assume that your same id will contain different emails, you have to do below changes:-
<?php
$msql=$db->prepare("SELECT * from users where id=? order by id desc");
$msql->bind_param("i",$user_id);
$result = $msql->execute(); // assign to a variable
//$msql = $msql->get_result(); //you are over-writing to one variable which is not correct
//$msql = $msql->num_rows; //you are over-writing to one variable which is not correct
while($usercount=$result->fetch_assoc()){
$Email = $usercount['email'];
$FirstName = $usercount['first_name'];
$LastName = $usercount['last_name'];
?>
<strong><?php echo $FirstName.' '.$LastName;?></strong> <!-- send mail id to the url too otherwise how's you will get the email id to save it into SESSION-->
<?php } ?>
AND
<?php
if(isset($_GET['navigate']) && $_GET['navigate'] == "true"){
$_SESSION['email'][] = $_GET['email']; // assign each mail to SESSION ARRAY not SESSION variable
header('location: nextpage.php');
}
?>
AND
echo "<pre/>";print_r($_SESSION['email']); //to see all emails.
Note:- You have to write session_start(); on top of your php page just after <?php if you want to work with SESSION on that page.

Pass value from one PHP file to another

I'm trying to pass a value which is input into a box on one Php page (itinerary.php) into another Php page ('submit.php') so it can, from there, be saved into a database. But I can't quite figure out how to get it across. I've tried using GET as you can see from code below, but I am already using a GET statement to receive and acknowledge another value from that very same page 'submit'. I guess I am overcomplicating it, but my knowledge of Php is still pretty limited at this stage so any ideas would be appreciated!
This is an extract from the itinerary.php file (it sits within a Bootstrap/Html framework. Note the entry which contains the input box for the sequence number).
<h3><br>YOUR ITINERARY</h3>
<?php
//Display contents of itinerary
if(!empty($_SESSION['itinerary'])){
//Retrieve details of each location in array from database
$query = "SELECT * FROM locations WHERE loc_id IN (";
foreach ($_SESSION['itinerary'] as $loc_id=>$value)
{$query.=$loc_id.',';}
$query = substr($query, 0, -1).')ORDER BY loc_id ASC';
$result = mysqli_query($db, $query);
echo'<table><tr><th colspan="5">LOCATIONS IN YOUR ITINERARY</th></tr>';
//Display locations in array
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
$loc_id = $row['loc_id'];
echo"<br><td>{$row['loc_name']}</td></tr><br>
<td>{$row['loc_desc']}</td>
<td><p>Seq. No</p><input type=\"text\" size=\"3\" name=\"sequence\" value=????????>NOT SURE WHAT TO ADD INTO THIS LINE TO RETAIN THE INFO THAT IS INPUT</td>
<td><a href=remove_loc.php?value=$loc_id>Remove location</a><br></br></td>
</tr><br></table>";
}//while
print_r($_SESSION);
mysqli_close($db);
}//if
else {echo '<p><br>Your itinerary is empty.<br></p>';}
echo '<br><p>
<a href=submit.php?submit>Save itinerary</a>
<a href=clear_itin.php?clear>Clear itinerary</a>
Your details
Logout
</p>';
?>
And this is where I am trying to receive it and then use it in a SQL command to add to the database. (Again, this is within a Bootstrap framework)You can ignore the first SQL Insert statement as it is passing other info in successfully anyway..
<div class="row">
<div class="col-md-9">
<?php
if (isset($_GET['sequence'])){
$sequence = $_GET['sequence'];
}//if
if (isset($_GET['submit'])){
$query = "INSERT INTO itineraries (user_id, date_created) VALUES (".$_SESSION['user_id'].", NOW())";
$result = mysqli_query($db, $query);
$itinerary_id = mysqli_insert_id($db);
$retrieve_locs = "SELECT * FROM locations WHERE loc_id IN (";
foreach ($_SESSION['itinerary'] as $id=>$value)
{$retrieve_locs.=$id.',';}
$retrieve_locs = substr($retrieve_locs, 0, -1).')ORDER BY loc_id ASC';
$result = mysqli_query($db, $retrieve_locs);
//Store items in itin_locs db
while ($row = mysqli_fetch_array ($result, MYSQLI_ASSOC)){
//This is the command I have been trying to use, commented out. The second one below this works fine, but obv doesn't input a sequence number.
//$insert_locs = "INSERT INTO itin_loc (itinerary_id, loc_id, sequenceNo) VALUES ($itinerary_id, ".$row['loc_id'].", $sequence)";
$insert_locs = "INSERT INTO itin_loc (itinerary_id, loc_id) VALUES ($itinerary_id, ".$row['loc_id'].")";
$insert_result = mysqli_query($db, $insert_locs);
echo mysqli_error($db);
if ($insert_result === FALSE) {
die("Query failed!" . mysql_error() . $insert_locs);}
}//while
mysqli_close($db);
echo"<p>Your itinerary is saved!. Itinerary number is #".$itinerary_id."</p><br>";
$_SESSION['itinerary']= NULL;
echo '<p>
Your details
Logout
</p>';
}//if
else {echo '<p>Your itinerary is empty.<br></br></p>';}
?>
Use a form on your HTML page to hold all the input fields in the table.
Also instead of anchor "a" tag use a submit button to submit the form to other page.
Use some thing like:
Send value of submit button when form gets posted

session id store on index page

this is login.php and its header location is index.php and i want to store session id on index page but nothing has been shown
<?php
#extract($_POST);
include("config.php");
$sql="select password,name,us.id as uid from us left join tblblo on (tblblo.maker=us.id) where name='$websitename' and password=md5('$password')";
$result=$db->query($sql);
if($count=mysql_num_rows($result)>0)
{
$row=mysql_fetch_assoc($result);
$_SESSION['name']=$row['name'];
$_SESSION['id']=$row['uid'];
header("location:http://".$_SESSION['name'].".domain.com");
}
else
{
//$_SESSION['sess_msg']="Invalid Web Name or Password!Try Again.";
//header("location:https://domain.com/login.php");
//exit;
}
?>
i want to store session id on index page but nothing has been shown
1) It's always good to write session_start(); in the very beginning of your code before outputting anything else..
<?php
session_start();
#extract($_POST);
include("config.php");
2) You're mixing up the deprecated mysql API's with the object_oriented ones.
Change this:
if($count=mysql_num_rows($result)>0)
{
$row=mysql_fetch_assoc($result);
$_SESSION['name']=$row['name'];
$_SESSION['id']=$row['uid'];
To this:
$count = $result->num_rows;
if($count > 0)
{
$row = $result->fetch_assoc());
$_SESSION['name']=$row['name'];
$_SESSION['id']=$row['uid'];
3) this is login.php and its header location is index.php and i want to store session id on index page but nothing has been shown
I think what you meant was to use/echo the session values on index.php rather store?
on your index.php (after successfully storing the sessions on login.php):
<?php
echo $_SESSION['name'];
echo $_SESSION['id'];
?>

Webpage Title user name

I want to put the name of the loggedin user as the title of the page. But I've no idea how to do it. I've tried several ways but each one show a parse error. here is my php code for logging in the user and then showing his details.
<?php
//if the login session does not exist therefore meaning the user is not logged in
if(strcmp($_SESSION['uid'],"") == 0){
//display and error message
echo "<center>You need to be logged in to user this feature!</center>";
}else{
//otherwise continue the page
//this is out update script which should be used in each page to update the users online time
$time = date('U')+50;
$update = mysql_query("UPDATE `employer` SET `online` = '".$time."' WHERE `id` = '".$_SESSION['uid']."'");
$display_query = mysql_query("SELECT * FROM employer WHERE `id` = '".$_SESSION['uid']."'");
echo "<table id='pageTable'><tbody><th>Your Details</th>";
echo "<tbody>";
while($row = mysql_fetch_array($display_query)){
echo "<tr><td>Name: </td><td>".$row['name']."</td><tr>";
$titlename = $row['name'];
echo "<tr><td>E-Mail ID: </td><td>".$row['email']."</td><tr>";
echo "<tr><td>Contact No.: </td><td>".$row['contact']."</td><tr>";
echo "<tr><td>Company: </td><td>".$row['company']."</td><tr>";
echo "<tr><td>Designation: </td><td>".$row['designation']."</td><tr>";
}
echo "</tbody>";
echo "</table>";
echo "<table><tr><td>";
echo '<div class="button">Logout</td></tr></table>';
//make sure you close the check if they are online
}
?>
You need to get the data you want before you output the <head> section of the page, then include a <title> element in it.
<title><?php echo htmlspecialchars($myTitle); ?></title>
Make sure you properly markup your page: doctype, html-head-body etc. You can do that and while the body is still 'open', state your php code by simply starting with <?php followed by your script.
Then, the relevant part of your loginname-as-title code:
<head>
<title><?php echo $loginName ?></title><!-- thanks to Berry Langerak for noting 'echo' was missing -->
</head>
<body>
<?php
where $loginName is of course your var for the login ID you want to show.
use below code to display loginname as title
echo '<script language="javascript">';
echo 'document.title = \''.$row['name'].'\'';
echo '</script>'

Categories