在我的PHP程序中,我有2个单选按钮和一个提交按钮。按钮1 =回显EST按钮2 =回显PST。这很好。问题是,在我选择一个选择之前,我的错误价值已经得到了回应。单击提交按钮后如何才能运行脚本? (以下代码);
<?php
if(isset($_POST['EST'])){
date_default_timezone_set('America/New_york');
$today = date("F, l jS Y g:i:s a");
echo $today;
}else if(isset($_POST['PST'])){
date_default_timezone_set('America/Los_Angeles');
$today = date("F, l jS Y g:i:s a");
echo $today;
}else{
echo 'Please select a choice!';
}
?>
<form action="index.php" method="POST">
Select your time zone: <br/>
EST: <input type="radio" name="EST"/>
PST: <input type="radio" name="PST"/>
<br/></br>
<input type="submit" value="Submit!" name="submit"/>
</form>
答案 0 :(得分:2)
你有两个选择,你可以用isset($_POST['submit'])
条件包装整个PHP块(可以用@ jeroen的条件替换或你可以将表单提交给一个单独的处理脚本。
方法1
if(isset($_POST['submit'])) {
// The submit button (and entire form) has been posted, continue:
if(isset($_POST['EST'])){
date_default_timezone_set('America/New_york');
$today = date("F, l jS Y g:i:s a");
echo $today;
}else if(isset($_POST['PST'])){
date_default_timezone_set('America/Los_Angeles');
$today = date("F, l jS Y g:i:s a");
echo $today;
}else{
echo 'Please select a choice!';
}
}
// Form goes here
方法2
form.html
<form action="submit.php" method="POST">
Select your time zone: <br/>
EST: <input type="radio" name="EST"/>
PST: <input type="radio" name="PST"/>
<br/></br>
<input type="submit" value="Submit!" name="submit"/>
</form>
submit.php
<?php
if(isset($_POST['EST'])){
date_default_timezone_set('America/New_york');
$today = date("F, l jS Y g:i:s a");
echo $today;
}else if(isset($_POST['PST'])){
date_default_timezone_set('America/Los_Angeles');
$today = date("F, l jS Y g:i:s a");
echo $today;
}else{
echo 'Please select a choice!';
}
答案 1 :(得分:0)
如果发出POST请求,您只想运行代码的第一部分。所以你应该把它包装成:
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
// your php code
}
答案 2 :(得分:0)
<?php
if (isset($_POST["submit"])){
if(isset($_POST['EST'])){
date_default_timezone_set('America/New_york');
$today = date("F, l jS Y g:i:s a");
echo $today;
}else if(isset($_POST['PST'])){
date_default_timezone_set('America/Los_Angeles');
$today = date("F, l jS Y g:i:s a");
echo $today;
}else{
echo 'Please select a choice!';
}
} else {
?>
FORM
<?php
}
?>
答案 3 :(得分:0)
试试这段代码:
<?php
if(isset($_POST['time_zone'])){
if ($_POST['time_zone'] == "EST")
{
date_default_timezone_set('America/New_york');
$today = date("F, l jS Y g:i:s a");
echo $today;
} else if($_POST['time_zone'] == "PST") {
date_default_timezone_set('America/Los_Angeles');
$today = date("F, l jS Y g:i:s a");
echo $today;
} else
echo 'Please select a choice!';
}
?>
<form action="index.php" method="POST">
Select your time zone: <br/>
EST: <input type="radio" name="time_zone" value="EST"/>
PST: <input type="radio" name="time_zone" value="PST"/>
<br/></br>
<input type="submit" value="Submit!" name="submit"/>
</form>
答案 4 :(得分:0)
其他答案都很好,但这样可以得到你想要的结果,而不需要做太多改变。
}else if(isset($_POST['submit'])){
echo 'Please select a choice!';
}