出功能问题

时间:2011-04-07 14:19:07

标签: php

我编写了关闭mysql会话的函数。

<?php
class mysql
{
    var $user;
    var $password;
    var $database;
    var $host;
    var $out;

    function mysql($username, $password, $database, $host)
    {
        $this->user = $username;
        $this->password = $password;
        $this->database = $database;
        $this->host = $host;
    }
    function connect()
    {
        $conn = mysql_connect($this->host, $this->user, $this->password, $this->database)
                or die("Error cannnot connect to mysql server");
        echo "Connected successfully to Mysql server";
    }
    function out()
    {
        mysql_close($this->out);
    }
}
$connect = new mysql('root','','test','127.0.0.1');
$connect->connect();
$connect->out();
?>

上面代码中的问题是什么?

4 个答案:

答案 0 :(得分:1)

您需要关闭$conn。现在你正在关闭函数返回的任何内容......这是不正确的。由于您只是建立了一个连接并且无论如何都没有跟踪它,所以只需这样做:

function out()
{
    mysql_close();
}

答案 1 :(得分:1)

将包含db连接的变量添加到对象实例变量:

<?php
class mysql
{
    var $user;
    var $password;
    var $database;
    var $host;
    var $out;
    var $conn;

    function mysql($username, $password, $database, $host)
    {
        $this->user = $username;
        $this->password = $password;
        $this->database = $database;
        $this->host = $host;
    }
    function connect()
    {
        $this->conn = mysql_connect($this->host, $this->user, $this->password, $this->database)
                or die("Error cannnot connect to mysql server");
        echo "Connected successfully to Mysql server";
    }
    function out()
    {
        mysql_close($this->conn);
    }
}
?>

答案 2 :(得分:0)

您需要在班级中存储$conn变量(例如$this->conn),然后拨打mysql_close($this->conn)

答案 3 :(得分:0)

mysql_connect不会将数据库名称作为参数。你必须使用mysql_select_db()。

另外,使用$ this-&gt; out代替$ conn。

所以代码是:

 function connect()
    {
        $this->out = mysql_connect($this->host, $this->user, $this->password)
                or die("Error cannnot connect to mysql server");
        mysql_select_db($this->database) or die('Cannot select db');
        echo "Connected successfully to Mysql server";
    }