2013-07-12 67 views
0

好吧,我正在考慮練習一些面向對象的目標。如果這個班級對於我想要完成的任務有點矯枉過正,請讓我知道,但我只是爲了練習而做。基本上我有這樣一個非常基本的表格,它所做的只是將姓名,電子郵件以及來自他們的評論或消息,並將其上傳到數據庫。我知道(實際上不知道,只是非常確定)它是類的uploadMessage函數。想知道是否有人能告訴我我哪裏會出錯。謝謝! 首先是消息類 -PHP類方法不起作用?

class message{ 
     public $name; 
     public $email; 
     public $message; 

     function __construct($name, $email, $message){ 
      $this->name = $name; 
      $this->email = $email; 
      $this->message = $message; 
     } 

     public function uploadMessage(){ 
      if(!isset($this->name) || !isset($this->email) || !isset($this->message)){ 
       throw new Exception("One of the fields was incorrectly typed."); 
      } else{ 

       $database = new DB("localhost","username","password","Personal_blog"); 
       $this->name = mysqli_real_escape_string($database->_db,$this->name); 
       $this->email = mysqli_real_escape_string($database->_db,$this->email); 
       $this->message = mysqli_real_escape_string($database->_db,$this->message); 
       $query = "INSERT INTO messages(name,email,message) VALUES('".$this->name."', '".$this->email."', '".$this->message."')"; 
       $results = $database->query($query); 
       if($results->affected_rows > 0){ 
        return true; 
       } 

      } 
     } 
    } 

並且在下面我使用實例化的類,並且也調用方法的代碼。

ini_set("display_errors",1); 
    include_once "blog_functions.php"; 
    @ $name = "eric" ;  //$_POST['name']; 
    @ $email = "email";  //$POST['email'];  USING FAKE VALUES HERE FOR TESTING 
    @ $message = "message"; //$_POST['message']; 



    echo "hey"; 

    try{ 
     $message = new message($name, $email, $message); 
     $message->uploadMessage(); 
    } 

正如你所看到的,我想通過$ _ POST方法取值從一種形式,但只是一些測試,我把它的一些隨機變量的值,這是行不通的。新的DB()方法來自另一個基本上只是擴展了php mysqli庫的類。並且該關閉的$ database - > _ db屬性實際上是mysqli處理程序,這是我用於mysqli_real_escape_string中的引用的東西。

+0

順便說一句,我認爲這是uploadMessage()方法,因爲當我採取了我的代碼,回聲「哎」的原因;作品。否則,我什麼都得不到。 –

+2

您可能想要從代碼示例中刪除您的用戶名和密碼。 –

+0

你知道那些'@'確實減慢了你的代碼嗎? – naththedeveloper

回答

0

嘗試:

$query = "INSERT INTO messages(`name`,`email`,`message`) VALUES('".$this->name."', '".$this->email."', '".$this->message."')";