Home > Backend Development > PHP Tutorial > How to delete data from database using PHP function?

How to delete data from database using PHP function?

WBOY
Release: 2024-05-04 22:24:02
Original
824 people have browsed it

PHP provides a variety of functions for deleting data from the database, including mysqli_query() and mysqli_affected_rows(). These functions can be used according to the following steps: 1. Establish a database connection; 2. Prepare an SQL query; 3. Execute the query; 4 . Check the number of affected rows.

如何使用 PHP 函数删除数据库中的数据?

How to use PHP functions to delete data from the database

PHP provides a variety of functions for deleting data from the database. This tutorial will introduce the use of these functions and provide practical examples.

Function

The following are commonly used functions in PHP for deleting database data:

  • mysqli_query(): Directly execute SQL DELETE Query.
  • mysqli_affected_rows(): Returns the number of deleted rows.

Usage

To use these functions to delete database data, follow these steps:

  1. Establish a database connection: Use mysqli_connect() Function establishes a connection to the database.
  2. Prepare SQL query: Write a DELETE query, specifying the table and conditions to delete data.
  3. Execute query: Use the mysqli_query() function to execute the query.
  4. Check the number of affected rows: Use the mysqli_affected_rows() function to check how many rows were deleted.

Practical case

The following is an actual case of deleting all records in the table named users:

<?php
// 建立数据库连接
$conn = mysqli_connect('localhost', 'root', '', 'database_name');

// 准备 SQL 查询
$sql = "DELETE FROM users";

// 执行查询
$result = mysqli_query($conn, $sql);

// 检查受影响行数
$affected_rows = mysqli_affected_rows($conn);

echo "受影响的行数:$affected_rows";
?>
Copy after login

Executing this code will Delete all records from the users table.

The above is the detailed content of How to delete data from database using PHP function?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template