【问题标题】:index undefined php with $_POST用 $_POST 索引未定义的 php
【发布时间】:2013-08-31 09:49:37
【问题描述】:
我正在尝试摆脱未定义的索引。每次我在不勾选框的情况下单击提交时,都会收到未定义的索引错误。
<html>
<head>
<title>Order</Title>
<style>
</style>
<body>
<form action = "order.php" method = "post">
Coffee:<p>
<input type = "checkbox" value = "coffee" name = "cappuccino"/>Capuccino<br>
</form>
</body>
</head>
</Html>
<?php
$capuccino = 3.75;
if(isset($_POST["submit"]))
{
if($_POST['cappuccino'] <> 'coffee')
{
$capuccino = 0;
}
}
?>
【问题讨论】:
标签:
php
html
post
undefined-index
【解决方案1】:
试试issetlike
<?php
if(isset($_POST["submit"]))
{
if(isset($_POST['cappuccino']) && $_POST['cappuccino'] <> 'coffee')
{
$capuccino = 0;
}
}
?>
您也可以使用!= 代替<>
$_POST['cappuccino'] != 'coffee'
【解决方案2】:
在 HTML 表单中,如果您不检查值,则不会发布该值。您应该测试它是否首先发布,因此您的 php 代码将类似于:
<?php
if(isset($_POST["submit"]))
{
if(isset($_POST['cappuccino']) && $_POST['cappuccino'] <> 'coffee')
{
$capuccino = 0;
}
}
?>
【解决方案3】:
你的条件应该是:
if(array_key_exists('cappuccino', $_POST) && isset($_POST['cappuccino']) && $_POST['cappuccino'] <> 'coffee')
【解决方案4】:
<html>
<head>
<title>Order</Title>
<style>
</style>
<body>
<form action = "order.php" method = "post">
Coffee:<p>
<input type = "checkbox" value = "coffee" name = "cappuccino"/>Capuccino<br>
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</head>
</Html>
<?php
$capuccino = 3.75;
if(isset($_POST["submit"]))
{
if(isset($_POST['cappuccino']) && !empty($_POST['cappuccino']) <> 'coffee')
{
$capuccino = 0;
}
}
?>