search
HomeBackend DevelopmentPHP TutorialPHP implements submitting form content to database

PHP implements submitting form content to database

Jan 25, 2020 pm 09:46 PM
phpsubmitdatabaseform

PHP implements submitting form content to database

First use php to create a simple database and table, and use phpMyAdmin to create the MySql database and table. For example, create a test database as follows:

<?php
// 创建连接
$conn = new mysqli("localhost", "uesename", "password");
// 检测连接
if ($conn->connect_error)
{ 
 die("连接失败: " . $conn->connect_error);}
 // 创建数据库
 $sql = "CREATE DATABASE test";
  if ($conn->query($sql) === TRUE)
  { 
  echo "数据库创建成功";
  } else { 
  echo "Error creating database: " . $conn->error;
  }
 $conn->close();
?>

Then use the CREATE TABLE statement to create a MySQL table and set the following fields.

(Related learning video tutorial sharing: php video tutorial)

id: It is unique, type is int, and select the primary key.

uesrname: User name, type is varchar, length is 30.

password: Password, type is varchar, length is 30.

confirm: Confirm password, type is varchar, length is 30.

email: Email, type is varchar, length is 30.

Then use the sql statement to create the database table. The code is shown as follows:

<?php
 // 创建连接
 $conn = new mysqli("localhost", "uesename", "password","test");
 // 检测连接
 if ($conn->connect_error)
 { 
 die("连接失败: " . $conn->connect_error);
 }
 // 使用 sql 创建数据表
 $sql = "CREATE TABLE login (
 id INT(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
 username VARCHAR(30) NOT NULL,
 password VARCHAR(30) NOT NULL,
 confirm VARCHAR(30) NOT NULL,
 email VARCHAR(30) NOT NULL,
 )ENGINE=InnoDB DEFAULT CHARSET=utf8 ";
 if ($conn->query($sql) === TRUE)
 { 
 echo "Table MyGuests created successfully";
 } else { 
 echo "创建数据表错误: " . $conn->error;
 }
 $conn->close();
?>

We have created the database and table above, and now we will create a simple front-end page for form registration. The form page here is very simple, with a few simple text boxes such as user name, password, password confirmation, registration email, etc. The code is as follows:

<!DOCTYPE html>
<html>
<head>
 <title>用户注册页面</title>
 <meta charset="UTF-8"/>
 <style type="text/css">
 *{margin:0px;padding:0px;}
 ul{
  width:400px;
  list-style:none;
  margin:50px auto;
 }
 li{
  padding:12px;
  position:relative;
 }
 label{
  width:80px;
  display:inline-block;
  float:left;
  line-height:30px;
 }
 input[type=&#39;text&#39;],input[type=&#39;password&#39;]{
  height:30px;
 }
 img{
  margin-left:10px;
 }
 input[type="submit"]{
  margin-left:80px;
  padding:5px 10px;
 }
 </style>
</head>
<body>
<form action="zhuce.php" method="post">
 <ul>
 <li>
  <label>用户名:</label>
  <input type="text" name="username" placeholder="请输入注册账号"/>
 </li>
 <li>
  <label>密 码:</label>
  <input type="password" name="password" placeholder="请输入密码" />
 </li>
 <li>
  <label>确认密码:</label>
  <input type="password" name="confirm" placeholder="请再次输入密码" />
 </li>
 <li>
  <label>邮 箱:</label>
  <input type="text" name="email" placeholder="请输入邮箱"/>
 </li>
 <li>
  <input type="submit" value="注册" />
 </li>
 </ul>
</form>
</body>
</html>

Next, you need to use PHP code to submit the information submitted by the new user to the database, and use the POST method to transfer and obtain the value.

First of all, you need to connect to the database and table created previously, because the user name, password and other information registered by the new user need to be saved in the corresponding fields in the table. Before storing the data in the database table, make some judgments and verifications on the submitted data. For example, user names, emails, etc. that do not meet the requirements need to be filtered and error prompts are needed. Also, if the user name is registered by other users, you need to be prompted that you will not be able to To use this username again, this is to first read the username that already exists in the database and then make a judgment.

To put it simply, the data submitted by the form is stored in variables, and then the password and verification code are judged. After they are correct, the user information is stored in the database and the database stores all the data in the user information table. Extract and print it out. To put it bluntly, the second half of the sentence is about data storage and retrieval. The specific code is as follows:

<?php
session_start();
header("Content-type:text/html;charset=utf-8");
$link = mysqli_connect(&#39;localhost&#39;,&#39;root&#39;,&#39;root&#39;,&#39;test&#39;);
if (!$link) {
 die("连接失败:".mysqli_connect_error());
}
$username = $_POST[&#39;username&#39;];
$password = $_POST[&#39;password&#39;];
$confirm = $_POST[&#39;confirm&#39;];
$email = $_POST[&#39;email&#39;];
if($username == "" || $password == "" || $confirm == "" || $email == "")
{
 echo "<script>alert(&#39;信息不能为空!重新填写&#39;);window.location.href=&#39;zhuce.html&#39;</script>";
} elseif ((strlen($username) < 3)||(!preg_match(&#39;/^\w+$/i&#39;, $username))) {
 echo "<script>alert(&#39;用户名至少3位且不含非法字符!重新填写&#39;);window.location.href=&#39;zhuce&#39;</script>";
 //判断用户名长度
}elseif(strlen($password) < 5){
 echo "<script>alert(&#39;密码至少5位!重新填写&#39;);window.location.href=&#39;zhuce.html&#39;</script>";
 //判断密码长度
}elseif($password != $confirm) {
 echo "<script>alert(&#39;两次密码不相同!重新填写&#39;);window.location.href=&#39;zhuce.html&#39;</script>";
 //检测两次输入密码是否相同
} elseif (!preg_match(&#39;/^[\w\.]+@\w+\.\w+$/i&#39;, $email)) {
 echo "<script>alert(&#39;邮箱不合法!重新填写&#39;);window.location.href=&#39;zhuce.html&#39;</script>";
 //判断邮箱格式是否合法
} elseif(mysqli_fetch_array(mysqli_query($link,"select * from login where username = &#39;$username&#39;"))){
 echo "<script>alert(&#39;用户名已存在&#39;);window.location.href=&#39;zhuce.html&#39;</script>";
} else{
 $sql= "insert into login(username, password, confirm, email)values(&#39;$username&#39;,&#39;$password&#39;,&#39;$confirm&#39;,&#39;$email&#39;)";
 //插入数据库
 if(!(mysqli_query($link,$sql))){
 echo "<script>alert(&#39;数据插入失败&#39;);window.location.href=&#39;zhuce.html&#39;</script>";
 }else{
 echo "<script>alert(&#39;注册成功!)</script>";
 }
}
?>

Recommended related articles and tutorials: php tutorial

The above is the detailed content of PHP implements submitting form content to database. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:脚本之家. If there is any infringement, please contact admin@php.cn delete
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 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.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment