要在 PHP 中进行简单的增删改查(CRUD)操作,可以按照以下步骤进行:
连接数据库
首先,确保你已经连接到数据库。以下是一个简单的连接代码示例:
```php
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";
// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);
// 检查连接
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
echo "连接成功";
?>
```
插入数据(Create)
使用 SQL `INSERT INTO` 语句插入数据:
```php
<?php
$sql = "INSERT INTO table_name (column1, column2, column3)
VALUES ('value1', 'value2', 'value3')";
if ($conn->query($sql) === TRUE) {
echo "新记录插入成功";
} else {
echo "插入记录时出错: " . $conn->error;
}
?>
```
查询数据(Read)
使用 SQL `SELECT` 语句查询数据:
```php
<?php
$sql = "SELECT id, column1, column2 FROM table_name";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// 输出数据
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Column1: " . $row["column1"]. " " . $row["column2"]. "
";
}
} else {
echo "0 结果";
}
?>
```
更新数据(Update)
使用 SQL `UPDATE` 语句更新数据:
```php
<?php
$sql = "UPDATE table_name SET column1='new_value' WHERE id=1";
if ($conn->query($sql) === TRUE) {
echo "记录更新成功";
} else {
echo "更新记录时出错: " . $conn->error;
}
?>
```
删除数据(Delete)
使用 SQL `DELETE` 语句删除数据:
```php
<?php
$sql = "DELETE FROM table_name WHERE id=1";
if ($conn->query($sql) === TRUE) {
echo "记录删除成功";
} else {
echo "删除记录时出错: " . $conn->error;
}
?>
```
关闭连接
完成操作后,关闭数据库连接:
```php
<?php
$conn->close();
?>
```