在函数之间传递数据库连接

时间:2011-08-19 01:13:28

标签: php mysql

我是PHP的新手,所以这可能是一个简单的问题。这是我用来更新数据库的类。问题是它在标记为 * 的行上不断给出错误,因为它找不到$ con,这显然在函数openconn()中。看来我无法将连接传递给另一个函数。我做错了吗?谢谢

class retreats {

    public $retreat_name = '';

    function openconn() {
        $con = mysql_connect("localhost","root","root");

        if (!$con)
        {
            die('Could not connect: ' . mysql_error());
        }
        mysql_select_db("PHPTest", $con);
    }


    function closeconn(){
        mysql_close($con);
    }


    function add_retreat(){
        openconn();
        $sql="INSERT INTO tbl_retreats (retreat_name) VALUES ('".$this->retreat_name."')";

        if (!mysql_query($sql,$con)) *******
        {
            die('Error: ' . mysql_error());
        }

        echo "Record Successfully Added";

        closeconn();

    }
}

4 个答案:

答案 0 :(得分:3)

$con是函数openconn的局部变量。尝试以这种方式更改您的代码:

class retreats {  

    public $retreat_name = ''; 

    private $con;

    function openconn() {
    $this->con = mysql_connect("localhost","root","root");

    if (!$this->con)
    {
        die('Could not connect: ' . mysql_error());
    }
        mysql_select_db("PHPTest", $this->con);
    }


    function closeconn(){
        mysql_close($this->con);      
    }


    function add_retreat(){  
        openconn();
        $sql="INSERT INTO tbl_retreats (retreat_name) VALUES ('".$this->retreat_name."')"; 

        if (!mysql_query($sql,$this->con))
        {
            die('Error: ' . mysql_error());
        }
            echo "Record Successfully Added";

        closeconn();  

    }     

   }  

答案 1 :(得分:1)

您需要先在班级中声明$con。只需将其放在public $retreat_name = '';

之后

public $retreat_name = ''; 
private $con;

之后,您可以使用$this关键字在其他功能中使用它。

mysql_close($this->con);

答案 2 :(得分:1)

代码的简单PDO端口......

<?php
class pdoDB{
    //PDO Connect
    function connect($host,$db,$user,$pass){
        $this->dbh = new PDO('mysql:host='.$host.';dbname='.$db, $user, $pass);
    }

    function query($query){
        $this->retreat_name = $query;
        $this->prepare();
    }

    function prepare(){
        /* Execute a prepared statement by binding PHP variables */
        $this->sth = $this->dbh->prepare('INSERT INTO tbl_retreats (retreat_name) VALUES (:value)');
        $this->sth->bindParam(':value', $this->retreat_name);
        $this->execute();
    }

    function execute(){
        $this->sth->execute();
    }

    function result(){
        if ($this->sth->rowCount() > 0) {
            return 'Record Successfully Added';
        }else{
            return 'Record Not Inserted';
        }
    }

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


$db = new pdoDB();
$db->connect('localhost','PHPTest','root','pass');

$db->query('Barcelona'); //or $db->query($_POST['retreat_name']);

echo $db->result();

$db->close();
?>

答案 3 :(得分:0)

事实证明你需要这样做

$this->openconn();

而不仅仅是

openconn();