How to use PHP to implement data addition, deletion, modification and query operations
In web development, it is often necessary to perform addition, deletion, modification and query operations on the database. As a popular server-side programming language, PHP provides a wealth of functions and classes to conveniently operate databases. This article will introduce how to use PHP to implement data addition, deletion, modification and query operations, and provide specific code examples.
In PHP, you can use mysqli or PDO to connect to the database. The following is a sample code for using mysqli to connect to the database:
$servername = "localhost"; $username = "root"; $password = ""; $database = "mydb"; // 创建连接 $conn = new mysqli($servername, $username, $password, $database); // 检测连接是否成功 if ($conn->connect_error) { die("连接失败: " . $conn->connect_error); }
Inserting data refers to the operation of adding new data to the database. The following is a sample code for inserting data into the database:
$sql = "INSERT INTO users (username, email) VALUES ('John Doe', 'john.doe@example.com')"; if ($conn->query($sql) === TRUE) { echo "数据插入成功"; } else { echo "数据插入失败: " . $conn->error; }
Deleting data refers to the operation of deleting data that meets specific conditions from the database. The following is a sample code for deleting qualified data from the database:
$sql = "DELETE FROM users WHERE id = 1"; if ($conn->query($sql) === TRUE) { echo "数据删除成功"; } else { echo "数据删除失败: " . $conn->error; }
Updating data refers to the operation of modifying existing data in the database. The following is a sample code for updating data in the database:
$sql = "UPDATE users SET email='new.email@example.com' WHERE id=1"; if ($conn->query($sql) === TRUE) { echo "数据更新成功"; } else { echo "数据更新失败: " . $conn->error; }
Querying data refers to the operation of retrieving data under specific conditions from the database. The following is a sample code for querying data from the database:
$sql = "SELECT * FROM users"; $result = $conn->query($sql); if ($result->num_rows > 0) { // 输出每一行数据 while($row = $result->fetch_assoc()) { echo "ID: " . $row["id"]. " - 用户名: " . $row["username"]. " - 邮箱: " . $row["email"]. "<br>"; } } else { echo "没有查询到数据"; }
Summary:
This article introduces how to use PHP to implement data addition, deletion, modification and query operations. Through the sample code of connecting to the database, inserting data, deleting data, updating data and querying data, we hope to help readers better understand and master the methods of PHP data operation.
The above is the detailed content of How to use PHP to implement data addition, deletion, modification and query operations. For more information, please follow other related articles on the PHP Chinese website!