我正试图从表单中获取值但是在没有isset()
的情况下调用时它给了我未定义的索引错误。
现在,当我使用isset()
时,它会给我未定义的变量错误。
我该如何解决这个问题?
<html>
<head></head>
<body>
<form action="conn.php" enctype="multipart/form-data" method="post">
<p>Enter Database Username: <input type="text" name="username"></p>
<p>Enter Password: <input type="password" name="pass"></p>
<p><input type="submit" value="submit"></p>
</form>
<?php
if (isset($_POST['username'])) {
$username=$_POST['username'];
}
if (isset($_POST['pass'])) {
$pass=$_POST['pass'];
}
echo($username);
echo($pass);
?>
</body>
</html>
答案 0 :(得分:2)
因为您的$username
和$pass
变量都未定义且未经检查或isset()
阻止
echo($username);
echo($pass);
首先使用空白值初始化这些变量
<?php $username='';$pass='';
if (isset($_POST['username'])) {
$username=$_POST['username'];}
if (isset($_POST['pass'])) {
$pass=$_POST['pass'];}
echo($username);
echo($pass);
?>
或通过在check block中回显来简化: -
if (isset($_POST['username'])) {
echo $username=$_POST['username'];}
if (isset($_POST['pass'])) {
echo $pass=$_POST['pass'];}
答案 1 :(得分:2)
是的,它是未定义的,因为你在if块的范围之外使用它,它首先检查存在。
仔细观察:
// if this fails
if (isset($_POST['username'])) {
$username=$_POST['username'];
}
// if this fails
if (isset($_POST['pass'])) {
$pass=$_POST['pass'];
}
// your echoing an undefined variable
echo($username);
echo($pass);
或者,您可以这样做:
if(isset($_POST['username'], $_POST['password'])) {
// isset() can handle multiple parameters to check for its existence, if one of them is undefined, then its false
$username = $_POST['username'];
$password = $_POST['password'];
echo $username . '<br/>' . $password;
}
答案 2 :(得分:2)
因为当未发布表单时,变量将不会被设置。这个 -
if (isset($_POST['username']) && isset($_POST['pass'])) {
$username=$_POST['username'];
$pass=$_POST['pass']
echo($username);
echo($pass);
}
或
$username = $pass = '';
if (isset($_POST['username'])) {
$username=$_POST['username'];}
if (isset($_POST['pass'])) {
$pass=$_POST['pass'];}
echo($username);
echo($pass);
答案 3 :(得分:2)
正如您所看到的,有很多方法可以设置初始变量......但您需要将它们设置为在没有警告的情况下回显它们:
// Set variables to post if set, else empty if not
$username = (isset($_POST['username']))? $_POST['username']: "";
$pass = (isset($_POST['pass']))? $_POST['pass']: "";
echo($username);
echo($pass);