Home > Article > Backend Development > How to insert data into database using PHP functions?
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.
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.
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(); ?>
Task: Insert a row of data into the table named "customers".
Steps:
mysqli_prepare()
) and parameter binding (mysqli_bind_param()
) To prevent SQL injection attacks. mysqli_affected_rows()
function to check whether the data was successfully inserted. 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!