所以我想以这种方式使用$user_country
:
- 当我在 URL 中没有
country=
时$user_country
我希望它是数据库中的国家/地区; -
当我在 URL 中
country=United States
时,我希望$user_country
从原始国家/地区从 db 更改为美国并坚持其值,直到下一个 URL 值更改country
;session_start(); $emailc=$_SESSION["email"]; $req1=mysql_query("SELECT country FROM users WHERE email='$emailc'"); $countryz= mysql_fetch_assoc($req1); //Get country from URL: $country = isset($_GET['country']) ? $_GET['country'] : null; //Check the URL to see if we change $user_country if(isset($country)){ $_SESSION['country']=$_GET['country']; } else{ $_SESSION['country']=$countryz['country']; } //Assign value to `$user_country` $user_country=$_SESSION['country'];
我的问题:
www.example.com?country=United States
在本例中$user_country
=美国。
刷新后$user_country
返回到数据库中的值。
我希望即使在刷新后$user_country
也等于美国,直到 URL 中国家/地区的值再次更改;
在 www.example.com?country=Canada之前,我希望$user_country
=美国,这样我就可以在将来的条件下使用它的值$user_country
当用户导航离开时,您正在将值从DB设置到会话中。所以更新你的代码(添加一个elseif)应该可以工作
if(isset($country)){
$_SESSION['country']=$_GET['country'];
} elseif (empty($_SESSION['country'])) {
$_SESSION['country']=$countryz['country'];
}
当用户登录或开始鞠躬您的网站时,您必须在$_SESSION
中为国家/地区提供一个基本值。
if (empty($_SESSION['country'])) {
$_SESSION['country'] = initializeCountry();
}
初始设置后,仅当设置了 $_GET 参数时,才必须更改值,因此您的代码如下所示:
if(isset($country)){
$_SESSION['country']=$_GET['country'];
}
没有 else 语句。
我认为您的问题发生在这一行中
$country = isset($_GET['country']) ? $_GET['country'] : null;
如果刷新页面,您的代码将国家/地区覆盖为 null 这就是为什么您必须检查 $_GET 是否存在,然后从会话中获取国家/地区
if ( isset($_GET['country']) ) {
$country = $_GET['country'];
} else {
$country = isset($_SESSION['country']) ? $_SESSION['country'] : null;
}
您的完整代码:
session_start();
$emailc=$_SESSION["email"];
$req1=mysql_query("SELECT country FROM users WHERE email='$emailc'");
$countryz= mysql_fetch_assoc($req1);
//Get country from URL:
// Add this code
if ( isset($_GET['country']) ) {
$country = $_GET['country'];
} else {
$country = isset($_SESSION['country']) ? $_SESSION['country'] : null;
}
//$country = isset($_GET['country']) ? $_GET['country'] : null;
//Check the URL to see if we change $user_country
if(isset($country)){
$_SESSION['country']=$_GET['country'];
}
else{
$_SESSION['country']=$countryz['country'];
}
//Assign value to `$user_country`
$user_country=$_SESSION['country'];
按如下方式编写代码:-
session_start();
$emailc=$_SESSION["email"];
$req1=mysql_query("SELECT country FROM users WHERE email='$emailc'");
$countryz= mysql_fetch_assoc($req1);
//Get country from URL:
$country = (isset($_GET['country']) && !empty($_GET['country'])) ? $_GET['country'] : $countryz['country'];
//Set session variable
$_SESSION['country']=$country;
//Assign value to `$user_country`
$user_country=$_SESSION['country'];
希望它能帮助你:)
有几个重要的错误。您应该:1)数据库应该选择何时使用else statemenet。2)我认为您想在
中使用if语句 $country = isset($_GET['country']) ? $_GET['country'] : null;
但我认为你应该使用
$country = (isset($_GET['country'])) ? $_GET['country'] : null;
改为 null,将其设置为值。你不需要做第二个如果。