How to pass POST variables with MVC?

2019-09-04 22:55发布

问题:

I am following this MVC guide to learn the basics of creating web apps with the MVC pattern.

I have set it all up and it works fine, currently the system works with urls of this form;

address.co.uk/controller/method/params

I understand how this can work, however how would this work when posting data? for example a login form, i have tried accessing the POST variables from the controller, how ever this doesn't work, im guessing this is due to the .htaccess file sends everything to the index.php?

UPDATE:

so i have created this basic form;

    <form name="input" action="register/newuser" method="post">
    Username: <input type="text" name="user" />
    password: <input type="text" name="pass" />
    <input type="submit" value="Submit" />
    </form> 

That submits data to this controller methods newuser;

function newuser()
{
    $data['user'] = $_POST["user"];
    $data['pass'] = $_POST["pass"];
    $this->loadView('view_register_result',$data);
}

Then finally the result page;

<body>
    <h1>Result</h1>

    im not sure? <br />
    user: <?php echo $data['user']; ?>
    pass: <?php echo $data['pass']; ?>
</body>

Is there any reason why this doesn't work?

回答1:

$_POST is a superglobal, meaning that it's available everywhere. Of course, it won't be filled unless you do an actual POST.

mod_rewrite in the .htaccess will only rewrite the URL, but it won't touch the $_POST, $_SESSION or $_COOKIE. Only the $_GET might be changed slightly, but that's beyond the scope of your question.

Edit
Your issue is definitely unrelated to the $_POST. Does passing $data as an argument to loadView add it to the template as $data, or does it add it as two separate variables: user and pass? In that case, try loadView('..', array('data' => $data))



回答2:

When your form is submitted you are still calling a controller in the MVC pattern. This works the same as any page. You can use the $_POST variable in your controller to caputer that information. You can also use the $_REQUEST variable as it contains both Post and Get.



回答3:

Your POST variables should always be accessible from the $_POST superglobal-array. If you fail to retrieve the values from there, it's either because the application bootstrapper is manually emptying it (i.e. to enforce usage of a dedicated library) or no POST variables were passed through with the request.

Either way, I encourage you to use an existing solution for MVC.

(Reinventing the wheel is cool for playing around and learning though.)