britchey britchey - 16 days ago 7
PHP Question

How to grab data from post to a class Object

I have been trying to write data from a form submit into a PHP class object. I'm using the following basic submit form.

<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>


I found a previous article, How to grab data from post to a class. Which works with my submit form.

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


I'm trying to figure out how I could echo $firstname, $lastname & $emailaddress. How can I access these for use elsewhere?

Answer

This is a quick and dirty way of doing this, since you want to write the values to a database, as you stated in comments: "Thanks Fred, I was referring to using the variables to write to MySQL.".

Simply use the $this->propertyName and assign each of them to a variable.

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

    }

Note:

Writing to a database would be an entirely different matter and would be out of the scope of the question.

Remember to use a prepared statement at the time of insertion in order to help prevent against an SQL injection.

Sidenote about the use of isset().

Using isset() is usually best when using radio buttons/checkboxes.

  • empty() is better when user input is involved.

Reference: