用php语言写一个图书管理系统
时间: 2023-07-20 22:04:48 浏览: 98
好的,以下是一个简单的图书管理系统的 PHP 代码示例:
1. 数据库连接
```php
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "library";
// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);
// 检查连接是否成功
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
?>
```
2. 创建图书表
```php
<?php
$sql = "CREATE TABLE books (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(30) NOT NULL,
author VARCHAR(30) NOT NULL,
genre VARCHAR(30) NOT NULL,
published_year INT(4) NOT NULL,
)";
if ($conn->query($sql) === TRUE) {
echo "Table books created successfully";
} else {
echo "Error creating table: " . $conn->error;
}
?>
```
3. 插入图书记录
```php
<?php
$sql = "INSERT INTO books (title, author, genre, published_year)
VALUES ('1984', 'George Orwell', 'Dystopian', '1949')";
if ($conn->query($sql) === TRUE) {
echo "新记录插入成功";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
?>
```
4. 显示图书记录
```php
<?php
$sql = "SELECT id, title, author, genre, published_year FROM books";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// 输出数据
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Title: " . $row["title"]. " - Author: " . $row["author"]. " - Genre: " . $row["genre"]. " - Published Year: " . $row["published_year"]. "<br>";
}
} else {
echo "0 结果";
}
?>
```
以上是一个简单的图书管理系统的 PHP 代码示例,你可以根据自己的需求进行修改和完善。
阅读全文