[英]PHP Self-referencing script
我正在尝试使用以下代码在 HTML 表单中嵌入一个自引用 PHP 脚本:
未定义的索引:conv
<form action = "<?php $_SERVER['PHP_SELF'] ?>" method = "post">
<input type = "number" id = "temp2" name = "temperature2" placeholder = "28">
<label for = "temp2"> degrees </label>
<select>
<option name = "conv" value = "f"> Fahrenheit </option>
<option name = "conv" value = "c"> Celsius </option>
</select>
<input type = "submit" value = "equals">
<?php
$type = $_POST["conv"];
$tmp = $_POST["temperature2"];
if ($type == "f") {
$newTmp = (9/5 * $tmp) + 32;
echo $newTmp . " degrees Celsius.";
}
elseif ($type == "c") {
$newTmp = (5 * ($tmp - 32)) / 9;
echo $newTmp . " degrees Fahrenheit.";
}
?>
</form>
我收到以下消息:
Notice: Undefined index: conv Notice: Undefined index: temperature2
当 PHP 脚本在另一个文件中时,一切正常。 有谁知道我做错了什么?
变量( $type = $_POST["conv"];
)直到表单被处理后才被设置。 做
if (!empty($_POST["conv"])) {
$type = $_POST["conv"];
}
您必须验证您发送的页面和 $_POST 是否存在。 并更正选择元素
<form action = "<?php $_SERVER['PHP_SELF'] ?>" method = "post">
<input type = "number" id = "temp2" name = "temperature2" placeholder = "28">
<label for = "temp2"> degrees </label>
<select name = "conv">
<option value = "f"> Fahrenheit </option>
<option value = "c"> Celsius </option>
</select>
<input type = "submit" value = "equals">
<?php
if(isset($_POST["temperature2"])) {
$type = $_POST["conv"];
$tmp = $_POST["temperature2"];
if ($type == "f") {
$newTmp = (9/5 * $tmp) + 32;
echo $newTmp . " degrees Celsius.";
}
elseif ($type == "c") {
$newTmp = (5 * ($tmp - 32)) / 9;
echo $newTmp . " degrees Fahrenheit.";
}
}
?>
</form>
这是我的答案......首先,最好验证一下,它是否已提交??,如果调用提交按钮,则代码继续休息。 否则你会得到错误。 此外,在您单击提交按钮之前,不会显示结果和变量。
<form action = "<?php $_SERVER['PHP_SELF'] ?>" method = "post"> <input type = "number" id = "temp2" name = "temperature2" placeholder = "28"> <label for = "temp2"> degrees </label> <select name = "conv"> <option value = "f"> Fahrenheit </option> <option value = "c"> Celsius </option> </select> <input type = "submit" name="submit" value = "equals"> <?php if(isset($_POST["submit"])) { $type = $_POST["conv"]; $tmp = $_POST["temperature2"]; if ($type == "f") { $newTmp = (9/5 * $tmp) + 32; echo $newTmp . " degrees Celsius."; } elseif ($type == "c") { $newTmp = (5 * ($tmp - 32)) / 9; echo $newTmp . " degrees Fahrenheit."; } } ?> </form>
每次加载页面时,您的 PHP 代码都会运行,而不仅仅是在有人按下提交时。 这意味着它在那里寻找$_POST['conv']
和$_POST['temperature2']
但没有找到任何东西,因为表单尚未发布。
你需要命名你的提交按钮,然后用这样的if
包围你的所有 PHP 处理:
<input type = "submit" name="mysubmit" value = "equals">
<?php
if (@$_POST['mysubmit']) {
$type = $_POST["conv"];
$tmp = $_POST["temperature2"];
if ($type == "f") {
$newTmp = (9/5 * $tmp) + 32;
echo $newTmp . " degrees Celsius.";
}
elseif ($type == "c") {
$newTmp = (5 * ($tmp - 32)) / 9;
echo $newTmp . " degrees Fahrenheit.";
}
}
?>
现在,它只会在有人实际提交某些内容时查看该 PHP 代码。 将@ 放在@$_POST['mysubmit'] 之前,这样您就不会遇到之前在这个新数组键上遇到的错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.