Table of Contents
php怎样实现用户的登录注册" >php怎样实现用户的登录注册
新建数据库名itcast , 表名user ,执行下面代码
目录结构
首先从注册前台页面register_html.php开始
注册后台页面register.php(注册即是新增)
登录前台页面login_html.php
登录后台页面login.php
最后是我们登录成功的inex.php页面
这里做的并不是很美观,大家可以在这个基础上增加好看的样式,增加两次密码是否相同的判断,使用正则实现注册格式的判断等等,这里就不一一讲了,目的主要是能实现简单的登录注册,嘻嘻!
输入注册信息
点击注册
注册成功,自动跳转到登录页面
输入刚刚注册的信息
点击登录
成功跳转到index.php页面
Home Backend Development PHP Tutorial php怎样实现用户的登录注册?(实例详解)

php怎样实现用户的登录注册?(实例详解)

Jun 13, 2016 pm 01:22 PM
php log in Register

本篇文章带大家来了解一下怎样使用PHP来实现简单的登录注册的功能,实现这个功能需要用到MySql的相关知识,希望对大家有帮助!

php怎样实现用户的登录注册?(实例详解)

php怎样实现用户的登录注册

最近学习中要使用PHP+MySql实现简单登录注册,看了很多简单案例后发现,并没有人通过PDO实现简单登录注册,要么就是Mysql和MySqli实现,就算实现了意义也不大,js就可以做的事情,没必要放到PHP中去,我却偏偏不相信,保留着一股倔劲,简单的实现了登录注册,下面请看代码,有错误的地方希望大佬们指教!

新建数据库名itcast , 表名user ,执行下面代码

create table user(
       id int unsigned primary key auto_increment,
       username varchar(10) not null comment '用户名',
       password char(20) not null comment '密码',
       email varchar(40) not null comment '邮箱'
)charset=utf8;

insert into user (username,password,email) values
('张三','123456','zhangsan@qq.com');
Copy after login

目录结构

在这里插入图片描述

首先从注册前台页面register_html.php开始

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>欢迎注册</title>
</head>
<form action="./register.php" method="post">
<table >
	<tr><td class="title" colspan="2">欢迎注册新用户</td></tr>
	<tr><th>用户名:</th><td><input type="text" name="username" /></td></tr>
	<tr><th>邮箱:</th><td><input type="text" name="email" /></td></tr>
	<tr><th>密码:</th><td><input type="password" name="password" id="pw1" /></td></tr>
	<tr><th>确认密码:</th><td><input type="password" id="pw2" /></td></tr>
	<tr><td colspan="2" class="td-btn">
	<input type="submit" value="提交注册" class="button" />
	<input type="button" value="返回登录" class="button" onclick="location.href=&#39;login.php&#39;"  />
	</td></tr>
</table>
</form>
</html>
Copy after login

注册后台页面register.php(注册即是新增)

<?php 
header (&#39;Content-type:text/html;charset=utf-8&#39;);
//数据库服务器主机名,端口号,选择的数据库,字符集
$dsn = "mysql:host=localhost;dbname=itcast;charset=utf8";
$user = &#39;root&#39;;         //数据库名
$pwd = &#39;root&#39;;          //数据库密码

try{
    $pdo = new PDO($dsn,$user,$pwd);
    
    //如果post表单不为空
    if(!empty($_POST)){
        
        //声明变量$fields,用来保存字段信息
        $fields = array(&#39;username&#39;,&#39;password&#39;,&#39;email&#39;);
        
        //声明$values,用来保存值信息
        $values = array();
        
        //遍历$fields,获取输入用户名、密码、邮箱的键和值
        foreach($fields as $k=>$v){
            
            $data = isset($_POST[$v]) ? $_POST[$v] : '';
            
            if($data=='') die($v.'字段不能为空!');
            
            //赋值给$fields数组
            $fields[$k] = "$v";
            
            //赋值给$values数组
            $values[] = "'$data'";
            
        }
        //将$fields数组以逗号连接,赋值给$fields,组成insert语句中的字段部分
        //implode — 将一个一维数组的值转化为字符串
        $fields = implode(',', $fields);
        
        //将$values数组以逗号连接,赋值给$values,组成insert语句中的值部分
        $values = implode(',', $values);
        
        //最后把$fields和$values拼接到insert语句中,注意要指定表名
        $sql = "insert into user ($fields) values ($values)";
        
        if($res = $pdo->query($sql)){
            //注册成功,自动跳转到会员中心
            echo '<script>alert("注册成功!");window.location.href="login_html.php";</script>';
        }else{
            die ('注册失败!');
        }
    }
    
}catch(PDOException $e){
    echo $e->getMessage().'<br>';
    echo $e->getLine().'<br>';
    echo $e->__toString().'<br>';
}
define('APP', 'itcast');
require './register_html.php';
Copy after login

登录前台页面login_html.php

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>欢迎登录</title>
</head>
<body>
    <form method="post" action="./login.php">
        <table>
        	<tr><td>欢迎登录</td></tr>
        	<tr><th>用户名:</th><td><input type="text" name="username" /></td></tr>
        	<tr><th>密码:</th><td><input type="password" name="password" /></td></tr>
        	<tr><td>
        	<input type="submit" value="登录" />
        	<input type="reset" value="重新填写" />
        	</td></tr>
        </table>
    </form>
</body>
</html>
Copy after login

登录后台页面login.php

<?php
header (&#39;Content-type:text/html;charset=utf-8&#39;);
//数据库相关信息
$dsn = "mysql:host=localhost;dbname=itcast;charset=utf8";
$user = &#39;root&#39;;         //数据库名
$pwd = &#39;root&#39;;          //数据库密码,根据自己的密码更改

try{
    $pdo = new PDO($dsn,$user,$pwd);
    
   //如果表单中不为空
    if(!empty($_POST)){
        
        //从表单中获取数据
        $username = isset($_POST[&#39;username&#39;]) ? trim($_POST[&#39;username&#39;]) : &#39;&#39;;
        $password = isset($_POST[&#39;password&#39;]) ? ($_POST[&#39;password&#39;]) : &#39;&#39;;

        //执行SQL语句
		$sql = "select `id`,`password` from `user` where `username`=&#39;$username&#39;";
		
		if($res = $pdo->query($sql)){          
				//登录成功,自动跳转到会员中心
				echo '<script>alert("登录成功");window.location.href="index.php";</script>';
		}else{
		    //否则提示登录失败
		    die('登录失败!');
		}
    }
}catch(PDOException $e){
    //这段用于出错的时候,方便告诉我们那里错了
    echo $e->getMessage().'<br>';
    echo $e->getLine().'<br>';      //显示错误所在多少行
    echo $e->__toString().'<br>';
}
define('APP', 'itcast');
require './login_html.php';

?>
Copy after login

最后是我们登录成功的inex.php页面

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
		<h1>登录成功!</h1>
</body>
</html>
Copy after login
这里做的并不是很美观,大家可以在这个基础上增加好看的样式,增加两次密码是否相同的判断,使用正则实现注册格式的判断等等,这里就不一一讲了,目的主要是能实现简单的登录注册,嘻嘻!

输入注册信息

在这里插入图片描述

点击注册

在这里插入图片描述

注册成功,自动跳转到登录页面

在这里插入图片描述

输入刚刚注册的信息

在这里插入图片描述

点击登录

在这里插入图片描述

成功跳转到index.php页面

在这里插入图片描述

大家如果感兴趣的话,可以点击《PHP视频教程》进行更多关于PHP知识的学习。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
24
PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

See all articles