[英]What I'm doing wrong? "session start"
The first code below should show random numbers between 10-400下面的第一个代码应该显示 10-400 之间的随机数
The second code should show random numbers between 400-3000第二个代码应该显示 400-3000 之间的随机数
If I use one code alone it will works correctly.如果我单独使用一个代码,它将正常工作。 But If I post both codes like this in one page the second code will work on the first code between 10-400.
但是,如果我在一个页面中发布这样的两个代码,则第二个代码将适用于 10-400 之间的第一个代码。
What I'm doing wrong?我做错了什么?
Here is my code:这是我的代码:
<?php
session_start();
if(isset($_SESSION['num'])){
$num = mt_rand($_SESSION['num']-5, $_SESSION['num']+5);
}else{
$num = mt_rand(10, 400);
}
echo $num . " Gold coin";
$_SESSION['num'] = $num;
?>
<?php
session_start();
if(isset($_SESSION['num'])){
$num = mt_rand($_SESSION['num']-5, $_SESSION['num']+5);
}else{
$num = mt_rand(400, 3000);
}
echo $num . " Pink Coin";
$_SESSION['num'] = $num;
?>
It's because you're using the same session variable for both pieces of code, and after your first piece you set $_SESSION['num']
(which will be a value between 10 and 400), so the second piece of code will then take the first if
branch and generate a value between the first value -5 and +5 (so it will be between 5 and 405).这是因为您对两段代码使用相同的会话变量,并且在第一段之后设置
$_SESSION['num']
(这将是 10 到 400 之间的值),所以第二段代码将取第一个if
分支并在第一个值 -5 和 +5 之间生成一个值(因此它将介于 5 和 405 之间)。 You should use different session variables for each coin type eg您应该为每种硬币类型使用不同的会话变量,例如
session_start();
if(isset($_SESSION['gold'])){
$gold= mt_rand($_SESSION['gold']-5, $_SESSION['gold']+5);
}else{
$gold= mt_rand(10, 400);
}
echo $gold. " Gold coin";
$_SESSION['gold'] = $gold;
if(isset($_SESSION['pink'])){
$pink= mt_rand($_SESSION['pink']-5, $_SESSION['pink']+5);
}else{
$pink= mt_rand(10, 400);
}
echo $pink. " Pink coin";
$_SESSION['pink'] = $pink;
Note you should only call session_start()
once.请注意,您应该只调用
session_start()
一次。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.