一个简单的PHP连接数据库封装例子

不使用任何框架,能将连接、操作数据库的方法写出来,再封装成类,其实是作为PHPer最基础的技能。记得一次面试时,一个并不太懂编程的面试官问我,如果当下让我上机操作,写出对数据库的操作包括增删改查,需要多长时间。自我感觉这个问题问得很没水平,但想要把它写好了,写出花来,还真就不简单。

<?php
//------------------------------------------------------------------------------------------ 
// ※Database()                   构造函数,数据库初始参数 
// ※Select()                     查询
// ※GetRows()                    返回查询的记录总数
// ※Insert()                     插入记录
// ※Update()                     更新
// ※Delete()                     删除
// ※Halt()                       中断并显示错误信息*/
//------------------------------------------------------------------------------------------ 
define("DATABASETYPE", "1");       //定义数据库类型:1为MySql;2为SQL Server;3为Oracle;4为Odbc
define("SERVER", "localhost");     //Host name or IP address of the database server
define("DATABASE", "dbName");   //要连接的数据库名
define("USER", "tableName");     //用于连接数据库的用户名
define("PASSWORD", "paswd");    //用于连接数据库的密码  

class Database {
    var $dbLink;                      //连接句柄 
    var $result;                      //查询句柄 
    var $insId;                       //Insert()成功返回AUTO_INCREMENT列的值
    var $rows;                        //返回数据数组
    var $numRows;                     //返回数据数目
    var $dbHost, $dbUser, $userPassword, $database;
    var $dbType = DATABASETYPE;
    var $msgFlag = "yes";            //yes:show the Mysql message ; no: die by show "Halted."

    function Database($dbHost = SERVER, $dbUser = USER, $userPassword = PASSWORD, $database = DATABASE) {
        switch ($this->dbType) {
            case 1:
                $this->dbLink = @mysql_pconnect($dbHost, $dbUser, $userPassword); // or die("Can't Connect to Remote Host!");
                @mysql_select_db($database, $this->dbLink); // or die ("Can't Connect to Remote Host!");
                break;
            case 2:
                break;
        }
        return true;
    }

    /* SQL:Select() 返回为false无结果 */

    function Select($table, $columns, $condition = 1) {
        $sql = "select $columns from $table where $condition ";
        $this->result = @mysql_query($sql, $this->dbLink);
        unset($this->rows);
        if ($this->result) {
            $i = 0;
            if (!($this->rows = array("$i" => @mysql_fetch_array($this->result))))
                return false;
            if (($this->numRows = @mysql_num_rows($this->result)) == 0)
                return false;
            while ($tempRows = @mysql_fetch_array($this->result)) {
                array_push($this->rows, $tempRows);
            }
        } else {
            $this->Halt($sql);
            return false;
        }
        return true;
    }

    /* SQL:GetRows() 返回查询的记录总数 */

    function GetRows($table, $condition = 1) {
        $sql = "select count(1) as count from $table where $condition";
        $this->result = @mysql_query($sql, $this->dbLink);
        if ($this->result) {
            $temp = @mysql_fetch_array($this->result);
            $this->numRows = $temp[count];
        } else {
            $this->Halt($sql);
            return false;
        }
        return $this->numRows;
    }

    /* SQL:Insert() */

    function Insert($table, $columns, $values) {
        $sql = "insert into $table ($columns) values ($values)";
        $this->result = @mysql_query($sql, $this->dbLink);
        if ($this->result)
            $this->insId = @mysql_insert_id($this->dbLink);
        else {
            $this->Halt($sql);
            return false;
        }
        return true;
    }

    /* SQL:Update() */

    function Update($table, $setings, $condition) {
        $sql = "update $table set $setings where $condition";
        $this->result = @mysql_query($sql, $this->dbLink);
        if ($this->result)
            $this->numRows = @mysql_affected_rows($this->result);
        else {
            $this->Halt($sql);
            return false;
        }
        return true;
    }

    /* SQL:Delete */

    function Delete($table, $condition) {
        $sql = "delete from $table where $condition";
        $this->result = @mysql_query($sql, $this->dbLink);
        if ($this->result)
            $this->numRows = @mysql_affected_rows($this->result);
        else {
            $this->Halt($sql);
            return false;
        }
        return true;
    }

    /* Halt():error message */

    function Halt($msg) {
        if ($this->msgFlag == "yes") {
            printf("<b>Database Query Error:</b> %s<br>n", $msg);
            printf("<b>MySql Error:</b> %s<br>n", mysql_error());
        }else
            echo "<META HTTP-EQUIV=REFRESH CONTENT='0;URL=../include/error.htm'>"; //自定一个出错提示文件
        return false;
    }
}

switch ($db->dbType) {
    case 1:
        @mysql_close();
        break;
    case 2:
        break;
}
$db = new Database();
?>

 

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注