How to implement PHP functions for adding, deleting, modifying, and querying data?
The PHP language is highly versatile and powerful, capable of implementing various types of functions, including CRUD operations. The following is a simple example demonstrating how to use PHP to implement basic CRUD functionality.
// 连接数据库
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
// 检查连接
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
// 查询数据
$sql = "SELECT id, name, email FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// 输出数据
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - 姓名: " . $row["name"]. " - 邮箱: " . $row["email"]. "<br>";
}
} else {
echo "0 结果";
}
// 插入数据
$sql = "INSERT INTO users (name, email) VALUES ('John Doe', 'john@example.com')";
if ($conn->query($sql) === TRUE) {
echo "新记录插入成功";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
// 更新数据
$sql = "UPDATE users SET email='john.doe@example.com' WHERE name='John Doe'";
if ($conn->query($sql) === TRUE) {
echo "记录更新成功";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
// 删除数据
$sql = "DELETE FROM users WHERE name='John Doe'";
if ($conn->query($sql) === TRUE) {
echo "记录删除成功";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
The above code examples demonstrate how to connect to a database, query data, insert data, update data, and delete data. In actual applications, you may need more specific logic and functionality to implement the CRUD operations. I hope the above examples are helpful to you.