用PHP+MySQL做一个图书管理系统并实现对数据库的增删改查等功能代码
时间: 2024-03-10 10:46:15 浏览: 121
好的,以下是一个简单的PHP+MySQL实现图书管理系统的示例代码:
1. 首先,连接数据库:
```php
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// 创建连接
$conn = mysqli_connect($servername, $username, $password, $dbname);
// 检测连接
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
```
2. 实现查询功能:
```php
<?php
$sql = "SELECT id, title, author, year_published FROM books";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// 输出每行数据
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. " - Title: " . $row["title"]. " - Author: " . $row["author"]. " - Year Published: " . $row["year_published"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
```
3. 实现插入数据功能:
```php
<?php
$title = $_POST['title'];
$author = $_POST['author'];
$year_published = $_POST['year_published'];
$sql = "INSERT INTO books (title, author, year_published) VALUES ('$title', '$author', '$year_published')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
```
4. 实现更新数据功能:
```php
<?php
$id = $_POST['id'];
$title = $_POST['title'];
$author = $_POST['author'];
$year_published = $_POST['year_published'];
$sql = "UPDATE books SET title='$title', author='$author', year_published='$year_published' WHERE id=$id";
if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
```
5. 实现删除数据功能:
```php
<?php
$id = $_POST['id'];
$sql = "DELETE FROM books WHERE id=$id";
if (mysqli_query($conn, $sql)) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
```
以上是一个简单的PHP+MySQL实现图书管理系统的示例代码,可以根据自己的需求进行修改和完善。
阅读全文