PHP数据库编程(4)之在线词典案例
# 在线词典系统 ## 系统介绍 本在线词典系统基于PHP和MySQL构建,旨在提供一个简单的查询接口,用户可以通过输入英文或中文单词来获取对应的词义。 ## 数据库设计 - **表名**: `words` - **字段**: - `id` (主键, 自增) - `enword` (英文单词) - `chword` (中文单词) - `enwordtype` (英文单词类型) - `chpinyin` (中文拼音) - `enwordread` (英文读音) ## 系统功能 1. **用户输入查询**: - 用户可以通过输入英文或中文单词来进行查询。 2. **查询结果展示**: - 查询到的结果会显示在页面上,包括词义、类型和拼音等信息。 ## 技术栈 - **前端**: HTML, CSS, JavaScript - **后端**: PHP - **数据库**: MySQL ## 源码结构 online_dictionary/ ├── main.php ├── sqlTool.php └── words.sql
## 代码示例 ### `main.php` ```php <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>在线词典</title> </head> <body> <h1>在线词典</h1> <form action="search.php" method="get"> <input type="text" name="query" placeholder="输入英文或中文单词" required> <button type="submit">查询</button> </form> <?php if (isset($_GET['result'])): ?> <div> <h2>查询结果</h2> <?= $_GET['result'] ?> </div> <?php endif; ?> </body> </html> search.php
<?php require 'sqlTool.php'; $query = isset($_GET['query']) ? $_GET['query'] : ''; if ($query) { $sqlTool = new SqlTool(); if (preg_match('/^[\x{4e00}-\x{9fa5}]+$/u', $query)) { $sql = "SELECT chword, enwordtype, chpinyin, enwordread FROM words WHERE chword LIKE '%{$query}%'"; } else { $sql = "SELECT chword, enwordtype, chpinyin, enwordread FROM words WHERE enword = '{$query}' LIMIT 0,1"; } $res = $sqlTool->excute_db1($sql); if (mysql_num_rows($res) > 0) { while ($row = mysql_fetch_assoc($res)) { echo "<p>{$query}<b>[{$row['enwordread']}]</b> - {$row['enwordtype']}." . $row['chword'] . "</p>"; } } else { echo "<p>查询没有词义</p>"; } mysql_free_result($res); } ?> sqlTool.php
<?php class SqlTool { private $conn; private $host = "localhost:3336"; private $user = "root"; private $password = "myoa888"; private $db = "phpstudy"; function __construct() { $this->conn = mysql_connect($this->host, $this->user, $this->password); if (!$this->conn) { die("连接数据库失败" . mysql_error()); } mysql_select_db($this->db, $this->conn); mysql_query("set names gbk", $this->conn); } // 完成 select public function excute_db1($sql) { $res = mysql_query($sql) or die(mysql_error()); return $res; } // 完成 update, delete, insert public function excute_dm1($sql) { $b = mysql_query($sql, $this->conn); echo "新添加的id=" . mysql_insert_id($this->conn); if (!$b) { return 0; // 失败 } else { if (mysql_affected_rows($this->conn) > 0) { return 1; // 成功 } else { return 2; // 没有行数影响 } } } } ?> 数据库初始化
CREATE DATABASE phpstudy; USE phpstudy; CREATE TABLE words ( id INT AUTO_INCREMENT PRIMARY KEY, enword VARCHAR(255) NOT NULL, chword VARCHAR(255) NOT NULL, enwordtype VARCHAR(255), chpinyin VARCHAR(255), enwordread VARCHAR(255) ); -- 插入示例数据 INSERT INTO words (enword, chword, enwordtype, chpinyin, enwordread) VALUES ('apple', '苹果', '名词', 'páo', 'páo'), ('banana', '香蕉', '名词', 'xiāngjīn', 'xiāngjiān'); 运行环境
- 确保安装了PHP和MySQL。
- 将代码文件上传到服务器或本地开发环境中。
- 配置数据库连接信息。
通过以上步骤,您可以在本地或服务器上运行这个简单的在线词典系统。