mysql扩展库应用---在线词典程序范例

1,在mysql中创建数据表words。

create table words(
    id int primary key not null auto_increment,
    enword varchar(32) character set utf8 not null,
    chword varchar(32) character set utf8 not null
);

2,编写数据库类,有以下代码可见,数据库类的封装不彻底,比如连接的关闭,需要调用后。自己手动关闭。

<?php
class SqlTool {
    private $conn = null;
    private $host = "127.0.0.1";
    private $user = "root";
    private $password = "123456";
    private $db = "test";

    //mysql扩展库操作mysql数据库步骤如下
    public function __construct(){
        //1.获取连接
        $this->conn = mysql_connect($this->host,$this->user,$this->password) or  die('连接错误:'.mysql_error());
        //2.选择数据库
        mysql_select_db($this->db,$this->conn) or die('选择数据库出错:'.mysql_error());
        //3.设置操作编码(建议有)
        mysql_query("set names utf-8");

    }

    //对数据表的查询操作
    public function execute_dql($sql){
        $rs = mysql_query($sql,$this->conn) or die('数据库查询失败:'.mysql_error());
        $rsList = array();
        if($rs){
            while($row = mysql_fetch_assoc($rs)){
                $rsList[] = array('id ' => $row['id'], 'enword'=> $row['enword'],'chword'=> $row['chword']);
            }
        }
        mysql_free_result($rs);
        return $rsList;
    }

    //对数据表的增删改操作
    public function execute_dml($sql){
        $rs = mysql_query($sql,$this->conn);
        if(!$rs){
            echo '数据库操作失败:'.mysql_error()."\n";
            $b = 0; //表示失败
        }else{
            if(mysql_affected_rows($this->conn) > 0){
                $b = 1; //数据表有变动
            }else{
                $b = 2; //没有影响数据表
            }
        }
        return $b;
    }

    //关闭conn连接
    public function closeConn(){
        mysql_close($this->conn);
    }
}

3,编写输入页面。

<html>
<head>
    <title>在线词典</title>
    <meta http-equiv="content-type" content="text/html;charset=gb2312" />
</head>
<body>
    <h1>查询英文</h1>
    <form action="onlineDictionary2.php" method="post">
        请输入英文:<input type="text" name="enword" />
        <input type="hidden" value="search" name="type" />
        <input type="submit" value="查询" />
    </form>
</body>
</html>

4,编写输出页面,调用的查询,查询完毕后,需要关闭资源。

<?php
require_once "SqlTool.class.php";
header("Content-type:text/html;charset=utf-8");
$en_word = $_POST['enword'];
if(!isset($en_word)){
    echo "输入为空,请<a href='onlineDictionary1.php'>点击</a>重新查询";
}

$sql = "select chword from words where enword ='{$en_word}' limit 0,1";
$sqlTool = new SqlTool();
$res = $sqlTool->execute_dql($sql);
if($res && $row=$res[0]){
    echo $row['chword'];
}else{
    echo "没有合适的翻译!";
}
$sqlTool->closeConn();

5,调用SqlTool.class.php类库,进行增删改操作如下,

<?php
require_once "SqlTool.class.php";
header("Content-type:text/html;charset=utf-8");

$sql = "insert into words(enword,chword) VALUES ('hello','你好')";
$sqlTool = new SqlTool();
$res = $sqlTool->execute_dml($sql);
if($res){
    echo "操作成功!";
}else{
    echo "操作失败!";
}
$sqlTool->closeConn();

 

posted on 2015-11-02 09:32  张三的哥哥  阅读(267)  评论(0编辑  收藏  举报