时间:2021-07-01 10:21:17 帮助过:2人阅读
直接举一个例子说明这个问题,首先我们的任务很简单,就是把mysql中test数据库的testtable表,按date时间类降序排序的结果查询到网页上。
如下图:

首先,我们编写一个model.php如下,
先声明一个私有的类成员$con作为这个类的全局变量。
可以把建立数据库连接的代码放在testtable这个数据库查询类的构造函数construct()里面,把关闭数据库连接的代码放在析构函 数destruct()里面,其中construct()与destruct()是php中的函数名保留关键字,也就是一旦声明这两个函数, 就被认为是构造函数与析构函数。
值得注意的是,为声明的私有类成员$con赋值,必须用$this->con的形式。不可以直接$con=xx,如果是$con=xx,php认为这个变量的作用范围仅在当前函数内,不能作用于整个类。
构造函数,要求一个变量$databaseName,此乃调用者需要查询的数据库名。
<?php  
class testtable{    
    private $con;   
    function construct($databaseName){  
        $this->con=mysql_connect("localhost","root","root");    
        if(!$this->con){    
            die("连接失败!");    
        }   
        mysql_select_db($databaseName,$this->con);    
        mysql_query("set names utf8;");    
    }  
    public function getAll(){            
        $result=mysql_query("select * from testtable order by date desc;");    
        $testtableList=array();    
        for($i=0;$row=mysql_fetch_array($result);$i++){  
            $testtableList[$i]['id']=$row['id'];  
            $testtableList[$i]['username']=$row['username'];    
            $testtableList[$i]['number']=$row['number'];    
            $testtableList[$i]['date']=$row['date'];    
        }    
        return $testtableList;    
    }  
    function destruct(){  
        mysql_close($this->con);    
    }  
}  
?>搞完之后,getAll()这个数据库查询类的查询方法,无须声明数据库连接与关闭数据库连接,直接就可以进行查询,查询完有析构函数进行回收。
在controller.php中先引入这个testtable查询类,再进行getAll()方法的调用,则得到如上图的效果:
<?php  
header("Content-type: text/html; charset=utf-8");     
include_once("model.php");    
    $testtable=new testtable("test");    
    $testtableList=$testtable->getAll();  
    echo "<table>";  
    for($i=0;$i<count($testtableList);$i++){    
        echo   
        "<tr>  
            <td>".$testtableList[$i]['id']."</td>  
            <td>".$testtableList[$i]['username']."</td>  
            <td>".$testtableList[$i]['number']."</td>  
            <td>".$testtableList[$i]['date']."</td>  
        </tr>";    
    }   
    echo "</table>";    
?>以上就是利用php的构造函数与析构函数编写Mysql数据库查询类的示例代码的详细内容,更多请关注Gxl网其它相关文章!