gongzhonghao.png
扫码关注我们
最新赞助活动温馨提示:自愿赞助服务器费用,学生和没有工作的整站资源免费下载!
头像

使用php的构造函数与析构函数编写MySQL数据库数据库查询类的示例代码

来源:http://erdangjiade.com/topic/2430.html 你好,世界。 2017-09-25 22:42浏览(13)

对于php查询Mysql数据库的model.php写法还不够完善,在每一个方法中还需要自己声明mysql的$con对象,同时自己关闭 mysql的$con对象。这样,如果查询方法一多,再无缘无故地增加了许多声明$con对象与关闭$con对象的代码。其实完全可以利用php的构造函 数与析构函数给数据库类各个查询方法的注入$con对象,同时自动在每次查询之后自动回收$con对象。

直接举一个例子说明这个问题,首先我们的任务很简单,就是把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数据库查询类的示例代码的详细内容,更多请关注二当家的素材网其它相关文章!

评论0
头像

友情提示:垃圾评论一律封号 加我微信:826096331拉你进VIP群学习群

1 2