无法在同一页面中编写HTML和PHP代码

时间:2016-10-28 05:58:02

标签: php html

我正在尝试为php表单编写一个简单的代码。我在与html相同的页面中编写了php代码。 php页面的名称是signup.php 但是我得到这样的错误:

  

注意:未定义的索引:nm in   第5行的C:\ xampp \ htdocs \ mini_project \ signup2.php

     

注意:未定义的索引:电子邮件   第6行的C:\ xampp \ htdocs \ mini_project \ signup2.php

如果我将php和html代码分成两个不同的页面,我的代码就没有问题。

为什么我不能在同一页面上编写php和html?我做错了什么?

我正在使用php 7.

  <?php

   include 'connect.php'

$nm = $_POST['nm'];
$email = $_POST['email'];
$password = $_POST['password'];
$cpassword = $_POST['cpassword'];
$type = $_POST['type'];
$remember = $_POST['remember'];
$signup = $_POST['signup'];

if (isset($signup))
{

  $query = "INSERT INTO user_details (nm,email,pass,user_type) VALUES ('$nm','$email','$password','$type')";
 $result = mysqli_query($conn,$query);
 }
?>


    <!DOCTYPE html>
     <html>
      <head>
   <meta name="viewport" content="width=device-width, initial-scale=1.0">

 <link href="css/bootstrap.min.css" rel="stylesheet" media="screen">
   <script src="js/jquery.min.js"></script>
 <script src="js/bootstrap.min.js"></script>

     <body>
     <div class="container">
    <div class="row">
        <div class="col-md-4 col-md-offset-4">
            <div class="login-panel panel panel-default">
                <div class="panel-heading">
                    <h3 class="panel-title">Please Sign In</h3>
                </div>
                <div class="panel-body">
                    <form role="form" method="post" action="signup.php">
                        <fieldset>
                            <div class="form-group">
                                <input class="form-control" placeholder="Please Enter Name" name="nm" id="nm" type="text" autofocus>
                            </div>
                            <div class="form-group">
                                <input class="form-control" placeholder="Please Enter E-mail" name="email" id="email" type="email">
                            </div >
                            <div class="form-group">
                                <input class="form-control" placeholder="Please Enter Password" name="password" id="password" type="password" value="">
                            </div>
                            <div class="form-group">
                                <input class="form-control" placeholder="Please Confirm Password" name="cpassword" id="cpassword" type="password" value="">
                            </div>
                            <div class="form-group">
                                <select class="form-control" align="center" name="type">
                                    <option value="0">Please Select User Type</option>
                                    <option value="1">I want to Hire</option>
                                    <option value="Second Year">I want to Work</option>
                                </select>
                            </div>
                            <div class="checkbox">
                                <label>
                                    <input name="remember" id="remember" type="checkbox" value="Remember Me">Remember Me
                                </label>
                            </div>
                            <!-- Change this to a button or input when using this as a form -->
                            <input type="submit" name="signup" id="signup" value="Signup" class="btn btn-lg btn-primary btn-block">

                        </fieldset>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

</body>

</html>

7 个答案:

答案 0 :(得分:5)

原因是因为您尚未提交表单,但您已尝试根据$_POST值定义变量。您需要检查是否先设置了值:

if (isset($_POST['nm'])) $nm = $_POST['nm'];
if (isset($_POST['email'])) $email = $_POST['email'];

或使用三元运算符:

$nm = isset($_POST['nm']) ? $_POST['nm'] : "";
$email = isset($_POST['email']) ? $_POST['email'] : "";

或在PHP 7中,简单地说:

$nm = $_POST['nm'] ?? "";
$email = $_POST['email'] ?? "";

答案 1 :(得分:1)

这是因为$ _POST数组中的各个键尚未设置 - 它们是在表单提交时设置的。

在尝试访问变量之前,您应首先测试变量是否已设置(使用isset()函数); e.g。

<?php
include 'connect.php'

if (isset($_POST['signup')) {
    $nm = $_POST['nm'];
    $email = $_POST['email'];
    // The rest of your code here...
}
?>

答案 2 :(得分:0)

无论页面是如何请求的,您都在运行代码,但只有在您向页面发布内容时才定义变量。您应该检查它是该页面的POST而不仅仅是常规的GET请求。如果您只是将所有代码移动到检查中以定义注册,那么可能正常工作。

答案 3 :(得分:0)

虽然您的页面在未设置$_POST数据时加载,但它不会呈现您提到的密钥。使用以下任何解决方案:

1)检查设置键:

<?php

include 'connect.php'

$nm = isset($_POST['nm']) ? $_POST['nm'] : "";
$email = isset($_POST['email']) ? $_POST['email'] : "";
$password = isset($_POST['password']) ? $_POST['password'] : "";
$cpassword = isset($_POST['cpassword']) ? $_POST['cpassword'] : "";
$type = isset($_POST['type']) ? $_POST['type'] : "";
$remember = isset($_POST['remember']) ? $_POST['remember'] : "";
$signup = isset($_POST['signup']) ? $_POST['signup'] : "";

if (isset($signup))
{

  $query = "INSERT INTO user_details (nm,email,pass,user_type) VALUES ('$nm','$email','$password','$type')";
 $result = mysqli_query($conn,$query);
 }
?>

2)或者你可以写下如下:

<?php

include 'connect.php'

if (isset($_POST['signup']))
{
$nm = $_POST['nm'];
$email = $_POST['email'];
$password = $_POST['password'];
$cpassword = $_POST['cpassword'];
$type = $_POST['type'];
$remember = $_POST['remember'];
$signup = $_POST['signup'];
  $query = "INSERT INTO user_details (nm,email,pass,user_type) VALUES ('$nm','$email','$password','$type')";
 $result = mysqli_query($conn,$query);
 }
?>

答案 4 :(得分:0)

你的php代码应该这样写:

 <?php
 if($_REQUEST['method'] == "POST") {
     include 'connect.php'

     $nm = $_POST['nm'] ?? "";
     $email = $_POST['email'] ?? "";
     $password = $_POST['password'] ?? "";
     $cpassword = $_POST['cpassword'] ?? "";
     $type = $_POST['type'] ?? "";
     $remember = $_POST['remember'] ?? "";
     $signup = $_POST['signup'] ?? "";

     if (isset($signup))
     {
        $query = "INSERT INTO user_details (nm,email,pass,user_type) VALUES ('$nm','$email','$password','$type')";
        $result = mysqli_query($conn,$query);
     }
 }
 ?>

答案 5 :(得分:0)

正如许多答案中已经说过的那样,您收到通知的原因是因为您正在尝试使用尚未发送到服务器的数据。为了避免这些,你首先要测试你是否确实已经发送了数据,然后才对它采取行动 这就是为什么它将它放入一个单独的文件中的原因,但如果你直接打开表单的目标URL(绕过表单),它仍会给你相同的通知。

请注意,即使已将内容发布到服务器,也并不意味着您期望的所有数据都会存在。有时浏览器的正常功能意味着他们不会发送一些字段(未经检查的复选框等),有时候用户尝试做一些你不希望他们做的事情。
这就是为什么检查每个价值也很重要的原因。不仅如果它存在,而且它是否在可接受的输入值/模式范围内。最后一位称为输入验证,通常使用filter_var()函数和its bretheren完成。

所以,将所有这些组合成一个脚本示例:     

include 'connect.php';

if (isset ($_POST['signup'])) {
    $error = process_signup ($conn);
}

/**
 * Processes the signup form, and saves the registration to the DB if successful.
 * Returns an error string detailing what went wrong, in case of errors.
 * 
 * @param PDO $db
 * @return void|string
 */
function process_signup (PDO $db) {
    // Testing for early exit conditions first, so that we don't do unnecessary work.
    $signup = filter_input (INPUT_POST, 'signup', FILTER_VALIDATE_BOOLEAN);
    if (!isset ($signup)) {
        // Since we're not signing up, just exit early.
        return;
    }

    // Using a variable to keep track of the validation status.
    $errors = array ();

    // Validate that the name only contains "word characters" as defined by regex.
    $options = array ('options' => array ('regexp' => '/^\w+\\z/u'));
    $nm = filter_input (INPUT_POST, 'nm', FILTER_VALIDATE_REGEXP, $options);
    if (!$nm) {
        // Add more descriptive error messages here.
        $errors[] = 'Name';
    }

    $email = filter_input (INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
    if (!$email) {
        $errors[] = 'Email';
    }

    // Create a regex that defines a _minimum_ level of password complexity.
    $password = filter_input (INPUT_POST, 'password', FILTER_VALIDATE_REGEXP, $options);
    if (!$password) {
        $errors[] = 'Password';
    }

    // If the password confirmation is set, and identical to the validated password, we're good.
    $cpassword = isset ($_POST['cpassword']) && $_POST['cpassword'] === $password ? true : false;
    if (!$cpassword) {
        $errors[] = 'Password confirmation';
    }

    // These are optional, so no need to add error messages if they're missing/wrong.
    $type = filter_input (INPUT_POST, 'type', FILTER_VALIDATE_INT);
    $remember = filter_input (INPUT_POST, 'remember', FILTER_VALIDATE_BOOLEAN);

    // If some of the validation failed, we need to stop here and tell the user about it.
    if (!empty ($errors)) {
        // Note that this is VERY rudimentary, you should do something more informative.
        $errors = "Following fields failed validation: ".implode (', ', $errors);
        return $errors;
    }

    // ALWAYS remember to hash the password!!!
    $password = password_hash ($password, PASSWORD_DEFAULT);

    // Using PDO as it's a bit easier than MySQLi.
    $query = "INSERT INTO user_details (nm,email,pass,user_type) VALUES (:name, :email, :password, :type)";
    $statement = $db->prepare ($query);
    $data = array (
            ':name' => $nm,
            ':email' => $email,
            ':password' => $password,
            ':type' => $type
    );

    if (!$statement->execute ($data)) {
        // Something went wrong with saving the data to the database. Handle it!
        return "Someting went wrong!";
    }

    // Everything is good, so redirect the user to a confirmation page.
    // Redirect prevents reloading the page from re-submitting the data.
    header ("Location: success.php");
    die ();
}

?>

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<link href="css/bootstrap.min.css" rel="stylesheet" media="screen">
<script src="js/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>

<body>
    <h3 class="panel-title">Please Sign In</h3>

    <form role="form" method="post" action="signup.php">
        <fieldset>
            <input class="form-control" placeholder="Please Enter Name" name="nm" id="nm" type="text" autofocus>
            <input class="form-control" placeholder="Please Enter E-mail" name="email" id="email" type="email">
            <input class="form-control" placeholder="Please Enter Password" name="password" id="password" type="password" value="">
            <input class="form-control" placeholder="Please Confirm Password" name="cpassword" id="cpassword" type="password" value="">

            <select class="form-control" align="center" name="type">
                <option value="0">Please Select User Type</option>
                <option value="1">I want to Hire</option>
                <option value="2">I want to Work</option>
            </select>

            <input name="remember" id="remember" type="checkbox" value="Remember Me">
            <label for="remember">Remember Me</label>

            <input type="submit" name="signup" id="signup" value="Signup" class="btn btn-lg btn-primary btn-block">
        </fieldset>
    </form>
</body>
</html>

请注意,我已经从中删除了很多(不必要的,恕我直言)HTML,并注意到这是一个相当粗略的例子。足以向您展示您需要采取的步骤,但尚未准备好在生产中使用。错误处理应该更加优雅,并向用户详细解释失败的内容以及这些字段中所需/允许的内容。

我还想指出在这里使用预备陈述,因为它们是正确防御SQL injections的唯一方法。

答案 6 :(得分:-1)

没人知道设置php.ini,.htaccess,connect.php是什么... 她的错误在什么阶段显示规则

为什么不在html文件中使用该设计:

if ($ _ POST) {
   $ Nm = isset ($ _ POST [ 'nm']) $ _ POST [ 'nm']: null;?
   ...
}

或者使用display_errors ...