2016-11-21 30 views
1

我一直在試圖從表單提交數據到提交到PHP類對象中。我正在使用以下基本提交表單。如何從郵件中抓取數據到類對象

<html> 
<body> 
<h2>Form Submit</h2> 
<form action='object_of_array2.php' method='POST'/> 
<input type="text" name='first_name' value=''/><br/> 
<input type="text" name='last_name' value=''/><br/> 
<input type="text" name='email_address' value=''/><br/> 
<input type='Submit' name='submit' value='GO'/> 
</form> 
</html> 
</body> 

我發現以前的文章How to grab data from post to a class。這與我的提交表單一起工作。

<?PHP 
class RegisterUser { 
    private $firstName; 
    private $lastName; 
    private $emailAddress; 

    function __construct() { 
     $this->firstName = isset($_POST['first_name']) ? $_POST['first_name'] : null; 
     $this->lastName = isset($_POST['last_name']) ? $_POST['last_name'] : null; 
     $this->emailAddress = isset($_POST['email_address']) ? $_POST['email_address'] : null; 
    } 

    function start() { 
     if (empty($this->firstName) || empty($this->lastName) || empty($this->emailAddress)) { 
      echo "Empty Post not allowed"; 
     } 
     else 
     { 
      // Do some stuiff 
      echo " Registration Done"; 
     } 
    } 
} 

$register = new RegisterUser(); 
if(!empty($_POST)) 
{ 
    $register->start(); 
} 
?> 

我試圖找出我怎麼能回聲$名字,姓氏$ $ & EMAILADDRESS。我如何訪問這些在其他地方使用?

+0

http://php.net/manual/en/language.oop5.php --- http://phpenthusiast.com/object- oriented-php-tutorials –

+0

*「我如何訪問這些在其他地方使用?」 - - 你將不得不詳細說明這一點。 –

+0

這是很平凡的東西;只是迴應成功。我會發佈一個答案,但不知道你想要用什麼,這讓我猶豫不決。你對我的評論保持沉默還增加了我的猶豫。我希望你喜歡閱讀我給你的那些鏈接,那裏有很多好東西。 –

回答

2

這是一個快速和骯髒的方法,因爲您想將值寫入數據庫,如您在評論中所述:「感謝Fred,我指的是使用變量來寫入MySQL。」

只需使用$this->propertyName並將它們分配給一個變量。

else 
     { 
      // Do some stuiff 
      echo " Registration Done" . "<br>"; 

    $var1 = $this->firstName; 
    $var2 = $this->lastName; 
    $var3 = $this->emailAddress; 


    echo $var1 . " " . $var2 . " " . $var3; 

    // write to database here using the assigned variables 

    } 

注:

寫入數據庫將是一個完全不同的問題,並就出了問題的範圍。

請記住在插入時使用預準備語句,以防止SQL注入。

旁註有關使用isset()

使用isset()通常是使用單選按鈕/複選框的最佳選擇。

  • empty()在涉及用戶輸入時更好。

參考:

+0

非常感謝!我正在使用$ register - > firstname ...等等。使用兩個或你的建議工作! – britchey

+0

@britchey你是最受歡迎的。 –