开发者

Out Function Problem

开发者 https://www.devze.com 2023-02-22 23:49 出处:网络
I wrote function that close the mysql session. <?php class mysql { var $user; var $password; var $database;

I wrote function that close the mysql session.

<?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 conn开发者_C百科ect 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();
?>

what the problem in the above code?


You need to close $conn. Right now you are closing whatever is returned by the function... which isn't correct. Since you are only making one connection and aren't keeping track of it anyway, just do this:

function out()
{
    mysql_close();
}


Add the variable that holds the db connection to the object instance variables:

<?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);
    }
}
?>


You need to store the $conn variable in the class (e.g. as $this->conn) then call mysql_close($this->conn)


mysql_connect doesn't take the database name as a parameter. You must use mysql_select_db() for that.

Also, use $this->out instead of $conn.

so the code would be:

 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";
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消