Home  >  Article  >  Backend Development  >  How to add data to the database in php (detailed operation explanation)

How to add data to the database in php (detailed operation explanation)

PHPz
PHPzOriginal
2023-04-04 14:00:272913browse

In website development, data addition operations are often required. This article will introduce how to use PHP to perform data addition operations.

1. Connect to the database

Before adding data, you first need to connect to the database. There are two ways to connect to the database: using mysqli or PDO. Let's take mysqli to connect to the database as an example.

<?php
//定义连接参数
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);

// 检测连接
if ($conn->connect_error) {
    die("连接失败: " . $conn->connect_error);
}
echo "连接成功";
?>

2. Processing form data

When processing form data in the background, the submitted form data needs to be filtered and verified to prevent SQL injection attacks.

To filter form data, you can use PHP's built-in function htmlspecialchars(), which converts special characters into HTML entities to prevent code injection.

You can use regular expressions to verify form data, such as verifying email format:

$email = test_input($_POST["email"]);
// 邮箱格式验证
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
  $emailErr = "无效的 email 格式";
}

3. Write SQL statements

Before adding data, you need to write SQL statements. SQL statements are divided into two types: queries that return results and operations that do not.

For data adding operations, we need to use the INSERT INTO statement. For example:

$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";

4. Execute the SQL statement

After completing the writing of the SQL statement, you need to execute the SQL statement through PHP code.

if ($conn->query($sql) === TRUE) {
  echo "新记录插入成功";
} else {
  echo "Error: " . $sql . "<br>" . $conn->error;
}

If the SQL query is successful, "New record inserted successfully" will be output. But if the SQL query fails, an error message will be output.

5. Close the database connection

After completing the data addition operation, you need to close the database connection.

// 关闭连接
$conn->close();

The above is an introduction to using PHP to add data.

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

Statement:
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