0

这是我的问题的第二部分:

创建/编辑 php 动态页面

我现在正在尝试将代码放在一起。如果您不想看我问题的第一部分,那么我会告诉您,我正在试验并制作一个允许用户发布特定城市活动的网站。首先用户使用下拉菜单选择状态,然后在下一页他们使用下拉菜单选择城市。一旦选择了城市,他们就会被带到 city.php,在这里我们使用数据库中的查询来显示人们为该特定城市发布的事件。无论如何,我想扩展城市并将 city.php 变成指向 events.php、jobs.php 或 forsale.php 的链接的索引。当用户点击其中一个链接时,仍会记住特定的城市,并会进行查询以提取这些信息。我只是在编码时遇到问题:

城市下拉菜单中的代码:

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;

来自 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();
}

我只是一个初学者,似乎无法理解如何正确使用会话来让我的网站正常工作。我也不确定我会用什么来确保我可以在 city.php 的子页面(事件、工作、待售)上进行正确的查询。

4

1 回答 1

0

一方面,您应该在开始的 php 标记下开始您的会话。至少为了其他人稍后查看此代码。

所以这篇庞大的帖子基本上是说“如何将选定的城市设置为会话变量并使用它从数据库中获取结果?”

好的,让我们从选择表单开始。让我们通过突破 php 并以正确的方式编写好的 ol html 来修改您的代码。始终避免在 php 中编写 html(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>

如果你不知道,这条线是一个三元运算符。您可以在该链接上看到一个示例...

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

它只是说如果行城市 ID 等于会话城市 ID,则添加selected="selected"到该选项的 html 中。

现在,在 php - 表单中您的操作属性指向的地方,您处理此请求......

<?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
}
?>

现在至少你的下拉菜单应该记住最后选择的城市。下一步是让您的结果关注该选择。显然你需要正确地逃避 $_SESSION['city_id'] 但对于这个例子让我们假设你已经这样做了......

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

有很多方法可以改善这一点,甚至尝试开始都是危险的。我假设您使用的是过程式编程习惯而不是 OOP,您知道转义用户输入,并且您对 php 有基本的了解。如果您有任何具体问题,我可以更新这篇文章。

于 2012-10-03T20:01:20.260 回答