用php构建一颗二叉树_用php构建一个简单的注册系统

用php构建一颗二叉树

Hello!

你好!

Most sites nowadays use a system of accounts linked to a database to keep track of user data, grant different levels of access, and to authenticate users when they are using your website.

如今,大多数网站都使用与数据库链接的帐户系统来跟踪用户数据,授予不同级别的访问权限以及在用户使用您的网站时对其进行身份验证。

In this tutorial, you will learn how to make a simple registration system for your website.

在本教程中,您将学习如何为您的网站制作一个简单的注册系统。

The article assumes you have a basic knowledge of the following languages:

本文假定您具有以下语言的基本知识:

  • HTML

    HTML
  • JavaScript

    JavaScript
  • PHP

    PHP
  • MySQL

    MySQL

You will need the following:

您将需要以下内容:

  • A web host (I personally use 000WebHost)

    一个虚拟主机(我个人使用000WebHost )

  • A code editor (I use VSCode)

    代码编辑器(我使用VSCode)
  • A MySQL database (hosted online)

    MySQL数据库(在线托管)

让我们开始吧! (Let’s get started!)

Image for post

Step 0 — Database Configuration:

步骤0 —数据库配置:

Before starting, make sure that your database has the correct fields for your purposes. Make a table in your database named ‘Accounts’, and add the following columns with the appropriate datatypes through your online database manager (such as PHPMyAdmin):

开始之前,请确保数据库具有适合您目的的正确字段。 在您的数据库中创建一个名为“ Accounts”的表,并通过您的在线数据库管理器(例如PHPMyAdmin)添加以下具有适当数据类型的列:

  • Username — text

    用户名-文本
  • UserID — int

    用户ID — int
  • Password — text

    密码-文字
  • Any other fields that you wish to collect (such as email address, age, etcetera)

    您希望收集的任何其他字段(例如电子邮件地址,年龄等)
Image for post
a sample sign-up page
样本注册页面
Image for post
A sample login page
登录页面示例

Step 1 — Making HTML Forms:

第1步-制作HTML表单:

In your website, you will have two forms; one for signing up, and one for logging in.

在您的网站中,您将有两种形式: 一个用于注册,另一个用于登录。

Making a sign-up form:

制作注册表格:

  • Make a form element in HTML

    在HTML中制作表单元素

  • Add inputs and labels for username, password, and other desired fields. (Don’t forget to set appropriate names for all the inputs)

    为用户名,密码和其他所需字段添加输入和标签。 (不要忘记为所有输入设置适当的名称)
  • Add a submit button with an appropriate name.

    添加具有适当名称的提交按钮。
<html>
  <body>
<form id = "sForm" method = "POST">
        <label>Username: </label><br><input name = "Susername" type = "text" placeholder = "Username" required><br><br>
        <label>Email: </label><br><input name = "Semail" type = "email" placeholder = "Email Address" required><br><br>
        <label>Password: </label><br><input name = "Spassword" type = "password" placeholder = "Password" pattern = ".{5,}" required><br><br>
        <button type = "submit" class = "submit" name = "signup">Sign Up</button>
</form>
</body>
</html>

Making a login form:

制作登录表单:

  • Make another form element in HTML

    在HTML中制作另一个表单元素

  • Add inputs and labels for username and password (again, don’t forget to set appropriate names for the inputs)

    添加用户名和密码的输入和标签(同样,不要忘记为输入设置适当的名称)
  • Add a submit button with an appropriate name.

    添加具有适当名称的提交按钮。
<html>
  <body>
    <form id = "lForm" method = "POST">
        <label>Username: </label><br><input name = "Lusername" type = "text" placeholder = "Username" required><br><br>
        <label>Password: </label><br><input name = "Lpassword" type = "password" placeholder = "Password" pattern = ".{5,}" required><br><br>
        <button type = "submit" class = "submit" name = "login">Login</button>
    </form>
  </body>
</html>

You can include both the forms on the same page, or on different pages.

您可以在同一页面或不同页面上同时包含这两个表单。

Step 2 — Connecting To Your Database

第2步-连接到数据库

Now that your database and your input forms are set up, you will have to set up a connection to your database using PHP. This will require you to know your database’s DB Name, DB Password, DB User, and DB Host.

现在已经建立了数据库和输入表单,您将必须使用PHP建立与数据库的连接。 这将要求您知道数据库的数据库名称数据库密码数据库用户数据库主机。

Setting up the connection is easy. The following code creates an object and connects you to your MySQL database, and then tests your connection to your database, returning an error if you are not connected.

建立连接很容易。 以下代码创建一个对象,并将您连接到MySQL数据库,然后测试您与数据库的连接,如果未连接,则返回错误。

<?php
$servername = <Your DB host>;
$username = <Your DB User>;
$password = <Your DB Password>;
$database = <Your DB Name>;
$mysqli = new mysqli($servername, $username, $password, $database);


if ($mysqli->connect_error) {
    die("Connection failed: " . $mysqli->connect_error);
}
?>

You will have to substitute your own details in the given code.

您将不得不在给定的代码中替换您自己的详细信息。

Once you are done with this file, name it ‘config.php’, and include the following snippet of code before your HTML in all your pages, as shown below:

使用完此文件后,将其命名为“ config.php”,并在所有页面HTML之前添加以下代码段,如下所示:

<?php
require_once "config.php";
?>
<html>
  ...

Step 3 — Sign-Up Procedure

第3步-注册程序

Once you have set up a connection to your database, you are ready to start adding accounts. However, you will need to write some code to get the input from the page, and insert records of new accounts into the database.

建立与数据库的连接后,就可以开始添加帐户了。 但是,您将需要编写一些代码来从页面获取输入,并将新帐户的记录插入数据库中。

Getting and sanitising the inputs:

获取和清理输入:

You will first get the inputs using the names of the inputs, and sanitise them to protect against common hacking techniques (such as SQL injection).

首先,您将使用输入的名称获取输入,并对它们进行清理以防止常见的黑客技术(例如SQL注入)。

<?php
if (isset($_POST['signup'])){
  unset($error);
  $username = $mysqli -> real_escape_string(stripslashes(strip_tags($_POST["Susername"])));
  $password = $mysqli -> real_escape_string(($_POST["Spassword"]));
  $email = $mysqli -> real_escape_string(stripslashes(strip_tags($_POST["Semail"])));
...

Here, the following line,

在这里,下一行

$mysqli->real_escape_string(stripslashes(strip_tags($_POST[“Susername”])));

$ mysqli-> real_escape_string(stripslashes(strip_tags($ _ POST [“ Susername”]))));;

Gets the username that the user inputted using the $_POST[“ ”] method, and sanitises the input. You must repeat this line for all the inputs.

获取用户使用$ _POST [“”]方法输入的用户名,并对输入内容进行清理。 您必须为所有输入重复此行。

Checking if username exists:

检查用户名是否存在:

Before allowing the user to register, we must first check if the username is already in use.

在允许用户注册之前,我们必须首先检查用户名是否已被使用。

To do this, we will first write a MySQL query to get all the records where the existing username matches the inputted username. We will then execute this query, and check if there are any such records. If an account with the inputted username already exists, an error message will be generated and sent to the user.

为此,我们将首先编写一个MySQL查询以获取现有用户名与输入用户名匹配的所有记录。 然后,我们将执行此查询,并检查是否有任何此类记录。 如果已经存在具有输入用户名的帐户,则会生成一条错误消息并将其发送给用户。

<?php
...
$sql = 'SELECT * FROM Accounts WHERE Name = "'.$username.'"';
  $result = $mysqli->query($sql);
  if ($result->num_rows > 0){
  $error = "This username is already taken!<br>";
  }
...

Adding New Accounts to Database

向数据库添加新帐户

If the user’s inputted username is unique, we will insert their details into the database, thus creating a new account.

如果用户输入的用户名是唯一的,我们将其详细信息插入数据库,从而创建一个新帐户。

However, before we insert a new record, we will need a new UserID. This code (given below) will get the last existing UserID in the table, and add 1 to it to generate a new UserID for our new account.

但是,在插入新记录之前,我们需要一个新的UserID。 此代码(如下所示)将获取表中最后一个现有的UserID,并将其添加1以为我们的新帐户生成一个新的UserID。

<?php
...
    $sql= "SELECT UserID FROM Accounts ORDER BY UserID DESC LIMIT 1";
    $result = $mysqli->query($sql);
    $row = $result->fetch_assoc();
    $LastId = $row['UserID']+1;
...
?>

After we have the UserID, you have everything you need to insert the new record into the database. You must now make a MySQL query to insert the details into the database, and then execute it.

获得UserID之后,您便拥有了将新记录插入数据库所需的一切。 现在,您必须进行MySQL查询,以将详细信息插入数据库,然后执行它。

<?php
...
$sql = "INSERT INTO Accounts (UserID, Name, Password, Email) VALUES ('$LastId','$username','$password','$email')";
...
?>

Step 4 — Login Procedure

步骤4 —登录过程

Your login procedure will be much simpler than your sign-up procedure, since you only need to verify whether the username exists in the database, and if yes, verify whether the password linked to the username is correct.

您的登录过程将比注册过程简单得多,因为您只需要验证数据库中是否存在用户名,如果是,请验证链接到用户名的密码是否正确。

This can easily be accomplished with this code:

可以使用以下代码轻松完成此操作:

<?php
...
else if (isset($_POST["login"])){
  $username = $mysqli -> real_escape_string(stripslashes(strip_tags($_POST["Lusername"])));
  $password = $mysqli -> real_escape_string($_POST["Lpassword"]);
  $sql = "SELECT * FROM Accounts WHERE Name = '$username'";
  $result = $mysqli->query($sql);
  if ($result->num_rows == 0){
    $error2 = "There is no account associated with this username!<br>";
  }
  else{
    $sql = "SELECT * FROM Accounts WHERE Name = '".$username."'AND Password = '".$password."'";
    $result = $mysqli->query($sql);
...
?>

In this code, the user input is sanitised, and a query is made to check if the inputted username exists in the database. If not, an error message is generated and sent to the user. If it does exist, then another SQL query is made to verify the password, and log in the user.

在此代码中,对用户输入进行了清理,并进行了查询以检查输入的用户名是否存在于数据库中。 如果不是,则会生成错误消息并将其发送给用户。 如果确实存在,那么将进行另一个SQL查询以验证密码,然后登录用户。

Step 5 — Adding PHP Sessions

第5步-添加PHP会话

You are very nearly finished with your registration system. However, to actually use the registration system, implementing sessions is very important. PHP sessions are a set of variables in which you can store your current user’s details.

您的注册系统即将完成。 但是,要实际使用注册系统,实施会话非常重要。 PHP会话是一组变量,您可以在其中存储当前用户的详细信息。

To do this, you must add this to the start of all of your websites:

为此,必须将其添加到所有网站的开头

session_start();

session_start();

This should come immediately after ‘<?php’, like so:

它应该紧接在'<?php'之后,如下所示:

<?php
session_start();
...

Now, you can begin storing your user’s data to the session! For this, you must store all the data in the session variables after they sign up and log in, like so:

现在,您可以开始将用户数据存储到会话中了! 为此,您必须在所有数据注册并登录后将它们存储在会话变量中,如下所示:

Storing data after signing up:

注册后存储数据:

<?php
...
     $_SESSION["loggedIn"] = TRUE;
     $_SESSION["username"] = $username;
     $_SESSION["userID"] = $LastId;
     $_SESSION["email"] = $email;
...
?>

Storing data after logging in:

登录后存储数据:

<?php
...
 if($result->num_rows == 1){
      $row = $result->fetch_row();
      $_SESSION["loggedIn"] = TRUE;
      $_SESSION["username"] = $row[1];
      $_SESSION["userID"] = $row[0];
      $_SESSION["email"] = $row[3];
    }
    else{
      $error2 = "Invalid username or password!<br>";
    }
...
?>

Step 6 — Adding Logout Functionality

步骤6 —添加注销功能

Good! You can now allow users to log in! But how do they log out? That is what we aim to add in this step. To do this, you must create a separate file, and link your logout button to open this file.

好! 现在,您可以允许用户登录! 但是他们如何注销? 这就是我们打算在此步骤中添加的内容。 为此,您必须创建一个单独的文件,并链接您的注销按钮以打开该文件。

<?php
session_start();
session_unset();
session_destroy();
header("location:Registration.php");
exit();
?>

This code will start your session, destroy all the existing session variables, end the session, and redirect your user back to the login page.

此代码将启动您的会话,销毁所有现有的会话变量,结束会话,并将您的用户重定向回登录页面。

Congratulations! You now know how to create a simple PHP registration system! You can apply CSS to make it look better, and implement it on your websites!

恭喜你! 您现在知道如何创建一个简单PHP注册系统! 您可以应用CSS使其外观更好,并在您的网站上实现它!

Full Signup/Login Code:

完整的注册/登录代码:

<?php
session_start();
require_once "config.php";


if (isset($_POST['signup'])){
  unset($error);
  $username = $mysqli -> real_escape_string(stripslashes(strip_tags($_POST["Susername"])));
  $password = $mysqli -> real_escape_string(($_POST["Spassword"]));
  $email = $mysqli -> real_escape_string(stripslashes(strip_tags($_POST["Semail"])));
  
  $sql = 'SELECT * FROM Accounts WHERE Name = "'.$username.'"';
  $result = $mysqli->query($sql);
  if ($result->num_rows > 0){
  $error = "This username is already taken!<br>";
  }
  else{
  $sql = 'SELECT * FROM Accounts WHERE Email = "'.$email.'"';
  $result = $mysqli->query($sql);
  if ($result->num_rows > 0){
  $error = "This email is being used by another account!<br>";
  }
  else{
    $sql= "SELECT UserID FROM Accounts ORDER BY UserID DESC LIMIT 1";
    $result = $mysqli->query($sql);
    $row = $result->fetch_assoc();
    $LastId = $row['UserID']+1;
    $sql = "INSERT INTO Accounts (UserID, Name, Password, Email) VALUES ('$LastId','$username','$password','$email')";
   if ($mysqli->query($sql)){
     $_SESSION["loggedIn"] = TRUE;
     $_SESSION["username"] = $username;
     $_SESSION["userID"] = $LastId;
     $_SESSION["email"] = $email;
   }
   else{
     echo("Error creating account. Please try again later.");
   }
  }
}
}
else if (isset($_POST["login"])){
  $username = $mysqli -> real_escape_string(stripslashes(strip_tags($_POST["Lusername"])));
  $password = $mysqli -> real_escape_string($_POST["Lpassword"]);
  $sql = "SELECT * FROM Accounts WHERE Name = '$username'";
  $result = $mysqli->query($sql);
  if ($result->num_rows == 0){
    $error2 = "There is no account associated with this username!<br>";
  }
  else{
    $sql = "SELECT * FROM Accounts WHERE Name = '".$username."'AND Password = '".$password."'";
    $result = $mysqli->query($sql);
    if($result->num_rows == 1){
      $row = $result->fetch_row();
      $_SESSION["loggedIn"] = TRUE;
      $_SESSION["username"] = $row[1];
      $_SESSION["userID"] = $row[0];
      $_SESSION["email"] = $row[3];
    }
    else{
      $error2 = "Invalid username or password!<br>";
    }
  }
}
?>
<!DOCTYPE HTML>
<html>
  <body>
      <h1>Sign Up</h1><br>
      <form class = "submitPres" id = "sForm" method = "POST">
        <label>Username: </label><br><input name = "Susername" type = "text" placeholder = "Username" required><br><br>
        <label>Email: </label><br><input name = "Semail" type = "email" placeholder = "Email Address" required><br><br>
        <label>Password: </label><br><input name = "Spassword" type = "password" placeholder = "Password" pattern = ".{5,}" required><br><br>
        <span class= "error">
          <?php
          if (isset($error)){
            echo ($error);
          }
          ?>
        </span>
        <button type = "submit" name = "signup">Sign Up</button>
      </form>
      <h1>Login</h1>
      <form class = "submitPres" id = "lForm" method = "POST">
        <label>Username: </label><br><input name = "Lusername" type = "text" placeholder = "Username" required><br><br>
        <label>Password: </label><br><input name = "Lpassword" type = "password" placeholder = "Password" pattern = ".{5,}" required><br><br>
        <span class= "error">
          <?php
          if (isset($error2)){
            echo ($error2);
          }
          ?>
        </span>
        <button type = "submit" class = "submit" name = "login">Login</button>
      </form>
  </body>
</html>

I hope you found this helpful!

希望对您有所帮助!

Thanks,

谢谢,

Saumya Shah

Saumya Shah

翻译自: https://medium.com/@saumyashah717/building-a-simple-registration-system-with-php-89d6218a063c

用php构建一颗二叉树

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值