php 连接数据库 进行增删改查
时间: 2023-07-09 19:38:43 浏览: 98
好的,以下是 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);
}
```
增加记录:
```php
// 插入一条新记录
$sql = "INSERT INTO table_name (column1, column2, column3)
VALUES ('value1', 'value2', 'value3')";
if ($conn->query($sql) === TRUE) {
echo "新记录插入成功";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
```
删除记录:
```php
// 删除一条记录
$sql = "DELETE FROM table_name WHERE id=3";
if ($conn->query($sql) === TRUE) {
echo "记录删除成功";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
```
修改记录:
```php
// 更新一条记录
$sql = "UPDATE table_name SET column1='value1', column2='value2' WHERE id=2";
if ($conn->query($sql) === TRUE) {
echo "记录更新成功";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
```
查询记录:
```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"]. " - column2: " . $row["column2"]. "<br>";
}
} else {
echo "0 结果";
}
```
以上就是 PHP 连接数据库进行增删改查的示例代码。
阅读全文