php数据库增删改查代码
时间: 2023-10-16 21:06:39 浏览: 103
PHP对数据库的增删改查
以下是一个简单的 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 "添加数据失败: " . $conn->error;
}
```
更新数据:
```php
$sql = "UPDATE table_name SET column1='new_value' WHERE id=1";
if ($conn->query($sql) === TRUE) {
echo "数据更新成功";
} else {
echo "更新数据失败: " . $conn->error;
}
```
删除数据:
```php
$sql = "DELETE FROM table_name WHERE id=1";
if ($conn->query($sql) === TRUE) {
echo "数据删除成功";
} else {
echo "删除数据失败: " . $conn->error;
}
```
查询数据:
```php
$sql = "SELECT * 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
$conn->close();
```
阅读全文