2011-08-19 44 views
0

我在PHP中相当新,所以也许这是一个简单的问题。这是我用来更新数据库的类。问题在于,它在标记为*的行中总是给我一个错误,因为它找不到$ con,这在openconn()函数中很清楚。看来我无法将连接传递给另一个函数。我是不是做错了什么?谢谢在函数之间传递db连接

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(); 

    } 
} 
+0

你不返回连接处理程序。 ''openConn()''con''' –

+2

Allen,我建议你阅读[面向对象编程(OOP)]的基础知识(http://www.php.net/manual/en/language.oop5)。 basic.php)和[属性](http://www.php.net/manual/en/language.oop5.properties.php) –

回答

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(); 

    }  

    } 
+0

谢谢..我会试试这个。 – Allen

1

您需要在类首先声明$con。只要把它的public $retreat_name = '';

后把

public $retreat_name = ''; 
private $con; 

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

mysql_close($this->con); 
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(); 
?> 
0

原来你需要这样做

$this->openconn(); 

,而不是仅仅

openconn();