php增删改查mysql实例
时间: 2023-07-07 13:37:49 浏览: 132
好的,以下是一个简单的 PHP 增删改查 MySQL 的示例:
连接 MySQL 数据库:
```php
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);
// 检测连接
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
echo "连接成功";
?>
```
插入数据:
```php
<?php
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";
if ($conn->query($sql) === TRUE) {
echo "新记录插入成功";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
```
查询数据:
```php
<?php
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// 输出每行数据
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 结果";
}
$conn->close();
?>
```
更新数据:
```php
<?php
$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";
if ($conn->query($sql) === TRUE) {
echo "记录更新成功";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
?>
```
删除数据:
```php
<?php
$sql = "DELETE FROM MyGuests WHERE id=3";
if ($conn->query($sql) === TRUE) {
echo "记录删除成功";
} else {
echo "Error deleting record: " . $conn->error;
}
$conn->close();
?>
```
以上是一个简单的 PHP 增删改查 MySQL 的示例。当然,实际应用中还需要考虑安全性和性能等因素。
阅读全文