使用PHP进行表单注册

时间:2013-05-17 01:01:22

标签: php session registration

请帮我解决此注册表格。对我来说很明显,我的PHP脚本中有一些错误。我的HTML表单如下所示:

<form action="script_1.php" method="post">
    <label for="name">Username:</label>
    <input type="text" name="name" />
    <label for="email">Email:</label>
    <input type="text" name="email" />
    <input type="submit" value="Register" />
</form>

我的php脚本如下:

<?php

    // Initialize session data
    session_start();

    /*
     * If the user is already registered, display a 
     * message letting them know.
     */

     if(isset($_SESSION['username'])) {
         echo "You're already registered as" .$_SESSION[username];  // Corrected on Stack Overflow
     }

     // Checks if the form was submitted 
     else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
         /*
          * If both the username and email fields were filled 
          * out, save the username in a session variable and 
          * output a thank you message to the browser. To
          * eliminate leading and trailing whitespace, we use
          * trim() function.
          */

          $uname = isset($_POST['username']) ? trim($_POST['username']) : '';   // Corrected on Stack Overflow
          $email = isset($_POST['email']) ? trim($_POST['email']) : '';         // Corrected on Stack Overflow

          if(!empty($uname) && !empty($email)) {        // Corrected on Stack Overflow

              $_SESSION['username'] = $uname;

              echo "Thanks for registering! <br />",
              "Username: $uname <br />",
              "Email: $email <br />";
          }

          /*
           * If the user did not fill out both fields, display
           * a message letting them know that both fields are 
           * required for registration.
           */
           else {
               echo "Please fill out both fields! <br />";
           }
     }

     // If the form was not submitted, displays the HTML form
     else {

?>

<?php } ?>

我需要它来检查输入字段是否包含某些内容然后执行操作。如果在这些字段中没有插入任何内容,我还需要它来执行不同的功能。

3 个答案:

答案 0 :(得分:0)

在表单脚本中,输入名称为

将此更改为

或更改您的script_1.php更改所有

$ _ POST [ '用户名']

$ _ POST [ '名称']

答案 1 :(得分:0)

在表单脚本中,输入名称为

<input type="text" name="name" />

将此更改为

<input type="text" name="username" />

或更改您的script_1.php更改所有

$_POST['username']

$_POST['name']

答案 2 :(得分:0)

在您[{1}}中,您使用FORM,因此您应该使用<input type="text" name="name" />  $_POST['name'] instead的{​​{1}}因为$_POST['username']根本不存在。您没有$_POST['username']名为textbox

username

如果你在php中回显变量,你应该这样做:

 echo "Thanks for registering! <br />",
              "Username: $uname <br />",
              "Email: $email <br />";