Home Backend Development PHP Tutorial How to submit php form to database? (detailed explanation)

How to submit php form to database? (detailed explanation)

Apr 22, 2017 pm 02:03 PM
php submit database form

To submit data to the server-side database, form form is used. This is the most common and simplest way to submit data. After filling in the form, the post is submitted to the background .php file, and after processing, it returns to the specified page. Finally, The page refreshed again, displaying the expected page. The following article will give you a detailed explanation of submitting PHP forms to the database through examples.

How to submit php form to database? (detailed explanation)

Generally when friends visit some websites and want to use the website or see more content on the website, the website will ask the user to register as a new user, and the website will The registration information of new users is stored in the database and retrieved when needed.

In this way, the website will first create its own database and corresponding tables. Here we use php to create a simple database and table, and use phpMyAdmin to create MySql database and table. For example, create a test database. The sample code is 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();
?>
Copy after login

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

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

uesrname: Username, 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 sql statements to create database tables. 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();
?>
Copy after login

We have created the database and tables 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 username, 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>
Copy after login

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, 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 and emails 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.

Simply put, the data submitted by the form is stored in the variable, and then the password and verification code are judged. After both are correct, the user information is stored The database extracts and prints out all the data in the table where user information is stored in the database.

To put it bluntly, the second half of the sentence is about data storage and extraction. 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>";
 }
}
?>
Copy after login

Friends can do various operations and attempts by themselves. After becoming proficient, they will have a certain in-depth understanding of form operations and database operations, laying a good foundation for future development. Foundation.

The above is the detailed content of How to submit php form to database? (detailed explanation). For more information, please follow other related articles on the PHP Chinese website!

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 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)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

MySQL: Simple Concepts for Easy Learning MySQL: Simple Concepts for Easy Learning Apr 10, 2025 am 09:29 AM

MySQL is an open source relational database management system. 1) Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2) Basic operations: INSERT, UPDATE, DELETE and SELECT. 3) Advanced operations: JOIN, subquery and transaction processing. 4) Debugging skills: Check syntax, data type and permissions. 5) Optimization suggestions: Use indexes, avoid SELECT* and use transactions.

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.

See all articles