PHP+MYSQL实验室增删除改查
时间: 2024-12-16 10:13:46 浏览: 2
php增删改查实例
PHP(Hypertext Preprocessor)是一种广泛使用的脚本语言,常用于Web开发,尤其是与MySQL数据库结合。MySQL是一个开源的关系型数据库管理系统。在PHP+MySQL实验环境中,你可以通过以下步骤进行基本的CRUD操作(Create、Read、Update、Delete):
1. **创建(Create)**:使用PHP连接到MySQL,执行SQL `INSERT`命令来插入数据到表格中,例如:
```php
$conn = mysqli_connect("localhost", "username", "password", "database");
$sql = "INSERT INTO users (name, email) VALUES ('John', 'john@example.com')";
if(mysqli_query($conn, $sql)) {
echo "新记录插入成功";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
```
2. **读取(Read)**:通过查询语句如`SELECT * FROM table_name`获取数据,然后用mysqli_fetch_assoc()等函数处理结果:
```php
$result = mysqli_query($conn, "SELECT * FROM users WHERE id=1");
while ($row = mysqli_fetch_assoc($result)) {
echo "Name: " . $row["name"] . ", Email: " . $row["email"];
}
```
3. **更新(Update)**:使用`UPDATE`语句修改已有记录的数据:
```php
$sql = "UPDATE users SET email='new_email@example.com' WHERE id=1";
mysqli_query($conn, $sql);
```
4. **删除(Delete)**:使用`DELETE FROM`语句删除特定记录:
```php
$sql = "DELETE FROM users WHERE id=1";
mysqli_query($conn, $sql);
```
完成以上操作后别忘了关闭数据库连接:
```php
mysqli_close($conn);
```
阅读全文