2011-08-19 83 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();