PHP and mysql connections [closed]

与世无争的帅哥 提交于 2019-12-25 04:38:37

问题


Is it possible to create a connection in a PHP class file and use it in all of the different methods in the class? I am trying to open a connection in the constructor and i get an error when i get to the close connection method saying that the argument that I've provided in the mysql_close() statement isn't a valid MYSQL-Link souce.


Update: Ok I figured it out I had a variable misspelled.


回答1:


It is entirely possible, you just need to make the database link a class member:

class MyDBClass {
    var $sth;

    function __construct($host, $user, $pass) {
        $this->sth = mysql_connect($host, $user, $pass);
    }

    function close() {
        mysql_close($this->sth);
    }
}



回答2:


As long as the variable has the correct scope, it should work fine through the whole class. One way to do this would be to store the connection as a member variable, e.g.

$this->connection = mysql_connect(...);

This will make it visible to all class methods as long as you use the same method to retrieve it, e.g.

mysql_close($this->connection);


来源:https://stackoverflow.com/questions/978478/php-and-mysql-connections

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!