Home  >  Article  >  Backend Development  >  How to insert data into database using PHP functions?

How to insert data into database using PHP functions?

王林
王林Original
2024-05-03 10:18:01873browse

Inserting data into the database requires using PHP's mysqli_query() function. The steps are as follows: 1. Connect to the database. 2. Prepare query statements. 3. Prepare the statement. 4. Bind parameters. 5. Set the value to be inserted. 6. Execute the query. 7. Check for successful insertion. 8. Close the statement and database connection.

如何使用 PHP 函数向数据库中插入数据?

How to use PHP functions to insert data into the database

Inserting data into the database is a basic operation for using PHP to interact with databases such as MySQL. This article will introduce the steps to insert data into the database using PHP's mysqli_query() function.

Code example

The following code example demonstrates how to use the mysqli_query() function to insert data into the database:

<?php
// 连接到数据库
$mysqli = new mysqli("localhost", "username", "password", "database_name");

// 准备查询语句
$query = "INSERT INTO table_name (column1, column2) VALUES (?, ?)";

// 准备语句
$stmt = $mysqli->prepare($query);

// 绑定参数
$stmt->bind_param("ss", $column1, $column2);

// 设置要插入的值
$column1 = "value1";
$column2 = "value2";

// 执行查询
$stmt->execute();

// 检查是否成功插入
if ($stmt->affected_rows > 0) {
    echo "数据已成功插入";
} else {
    echo "数据插入失败";
}

// 关闭语句和数据库连接
$stmt->close();
$mysqli->close();
?>

Practical case

Task: Insert a row of data into the table named "customers".

Steps:

  1. Connect to the database as shown in the code example above.
  2. Change the name of the table and the name of the column to be inserted.
  3. Set the value to be inserted to match your actual data.
  4. Run the query.
  5. Check whether the data is successfully inserted.

Note

  • Make sure to use statement preparation (mysqli_prepare()) and parameter binding (mysqli_bind_param()) To prevent SQL injection attacks.
  • Use the mysqli_affected_rows() function to check whether the data was successfully inserted.
  • Always close statements (mysqli_stmt_close()) and database connections (mysqli_close()) after completing the operation.

The above is the detailed content of How to insert data into database using PHP functions?. 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