-->

How to correctly use Sessions for dynamic pages

2019-09-08 01:25发布

问题:

This is the second part of my question from here:

Creating/editing a php dynamic page

I am now trying to put the code together. If you dont want to look at the first part of my question then ill tell you that i am experimenting and making a site that allows users to post events for a specific city. First the user uses a drop down menu to selct state, then on the next page they use a drop down menu to select the city. Once the city is selected they are taken to city.php where we use queries in our database to show events that people have posted for that particular city. Anyway i want to expand the city and turn city.php into the index where links to either events.php, jobs.php, or forsale.php will be located. When a user clicks on one of those links the particular city will still be remembered and a query will be done to pull out those info. Im just having problems coding:

Code from city drop down menu:

while($result = mysqli_fetch_array($doQuery)){
// $result contains id (cid) and name (cname) for each city
// $result - current row
// here we add HTML code for option "dynamically"
    echo "<option value='".$result["cid"]."'>".$result["cname"]."</option>";
    session_start();
    $_SESSION['cname'] = $city;

code from city.php:

session_start();
$_SESSION['cname'] = $city;
// import dbconnect.php
// we use require(not include) to stop the script if such file does not exist
// we use "once" because we do not need to establish dbconnection if it already exists
require_once("dbconnect.php");
// all data which we get from cityByState.php are stored in $_POST superglobal array
// in our case we have only one field "city" so we can get city id from $_POST["city"]
// also we use intval function for security purposes. It converts variable to integer.
$cityId = intval($_REQUEST["city"]);
// query which gets all info about required city
$query = "select * from cities where id=$cityId";
// run the query and handle possible errors
if(!($doQuery = mysqli_query($db, $query))){
    echo "Can not get info about the city!"; exit();
}

I am just a beginner and can't seem to understand how to properly use sessions to get my site to work properly. I am also not sure what i would use to insure that i can do the proper queries on the sub pages of city.php (events, jobs, forsale).

回答1:

For one, you should start your session right under the opening php tag. At the very least for the sake of anyone else looking at this code later.

So this massive post basically says "How do I set a selected city into a session var and use that to fetch results from the database?"

Ok, so let's start with the select form. Let's modify your code by breakingout of php and writing good ol html the right way. ALWAYS avoid writing html in php (echo '<a href="">'... etc)

<form id="city_select" action="" method="post">
    <fieldset>
        <select name="city">
        <?php while($result = mysqli_fetch_array($doQuery)): ?>
            <option value="<?php echo $result["cid"]; ?>" <?php echo ($result['cid'] == $_SESSION['city_id'] ? 'selected="selected"' : ''); ?>><?php echo $result["cname"]; ?></option>
        <?php endwhile; ?>
        </select>
        <input type="submit" name="submit" value="Submit">
    </fieldset>
</form>

in case you don't know, this line is a ternary operator. You can see an example at that link...

<?php echo ($result['cid'] == $_SESSION['city_id'] ? 'selected="selected"' : ''); ?>

It just says if the row city id is equal to the session city id, add selected="selected" to the html for that option.

Now, in php - where your action attribute in the form points to, you process this request...

<?php 
session_start();

if(isset($_POST['city']))
{
    $_SESSION['city_id'] = $_POST['city'];
    //you can do other processing here, like redirecting to the last page viewed to prevent double posting and that annoying re-submit form popup, etc
}
?>

Now at the very least your dropdown should remember the last selected city. Next step is to make your results care about that selection. obviously you need to properly escape $_SESSION['city_id'] but for this example let's just assume you're already doing that...

$query = "select * from cities where id=".$_SESSION['city_id'];

There are so many ways to improve this that it would be menacing to even try to begin. I make the assumption that you are using procedural programming habits and not OOP, that you are aware of escaping user input, and that you have a basic understanding of php. If you have any specific questions I may update this post.