Home  >  Article  >  Backend Development  >  How to delete database using php

How to delete database using php

PHPz
PHPzOriginal
2023-04-18 09:47:28543browse

In PHP, the deletion operation is a key step in deleting data from MySQL or other databases. Delete operations allow us to easily delete data or records we don't need. A very useful skill if you are doing web development work using PHP and need to delete data in a database. This article will introduce the steps to delete data in MySQL database using PHP.

Step 1: Connect to the MySQL database

In PHP, the MySQL function library that relies on PHP is connected to the database, so you must first use the following code to establish a connection with the database.

$conn = mysqli_connect("localhost", "root", "", "testdb"); // localhost = MySQL server address, root = MySQL username, testdb = Database name
if (!$conn) {

die("Connection failed: " . mysqli_connect_error());

}
?>

The above code connects to the testdb database in the local MySQL database. Now, the data in the database can be deleted after successful connection.

Step 2: Write a delete statement

To delete data in the MySQL database, you must write a DELETE statement. The following is an example DELETE statement.

$sql = "DELETE FROM users WHERE id=1";
if(mysqli_query($conn, $sql)){

echo "记录删除成功.";

} else {

echo "记录删除失败. " . mysqli_error($conn);

}
?>

In this example, we use the mysqli_query() function to execute the DELETE statement. Here, we delete the record with id 1 in the table named "users".

Step 3: Complete code example

The following is a complete code example to demonstrate how to use PHP to delete data in the MySQL database.

$conn = mysqli_connect("localhost", "root", "", "testdb");
if (!$conn) {

die("Connection failed: " . mysqli_connect_error());

}

$sql = "DELETE FROM users WHERE id=1";
if(mysqli_query($conn, $sql)){

echo "记录删除成功.";

} else{

echo "记录删除失败. " . mysqli_error($conn);

}

mysqli_close($conn);
?>

Summary

In this article, we learned how to use the MySQL function library in PHP Delete data in MySQL database by writing DELETE statement. Using these simple steps, you can easily delete unwanted data or records, thereby achieving better management of your MySQL database.

The above is the detailed content of How to delete database using php. 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