We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

creating model, saving it - how to "bind" a value?

lets see this easy example.

<?php
$robot = new Robots();
$robot->name = "RoboCop";
$robot->save();

Thats ok, but... if "name" comes from a form, how to clean / bind it?



17.5k
    $robot = Robots::findFirst(3);
    $robot->name = $this->cleanName($_POST['name']);
    $robot->save();

    public funciton cleanName($name) {
        //clean name

        return $name;
    }


43.9k

Hi,

use:


// Gets a variable from the $_POST superglobal applying filters if needed If no parameters are given the $_POST superglobal is returned
// see https://docs.phalcon.io/en/latest/api/Phalcon_Http_Request.html
$name = $this->request->getPost('name');

// for ORM, use bind parameters
// see https://docs.phalcon.io/en/latest/reference/models.html#binding-parameters
$robot = Robots::find(array(
    "conditions" => "name = :name:",
    "bind" => array("name" => $name)
    ));


28.1k

thanks, thats okay, but I dont want to query via this value but SAVE it :) sorry, it was unclear.



43.9k
Accepted
answer

use

$name = $this->request->getPost('name');



28.1k

aha. So this form: $this->request->getPost() escapes everything automatic?

Check out the docs on filtering and sanitizing.

If you want to be extra safe, you can do

$name = $this->request->getPost('name', 'string');

Or you can get the whole request, and then use the \Phalcon\Filter class when assigning your values to the object

$filter = new \Phalcon\Filter();
$data = $this->request->getPost();
$object->name = $filter->sanitize($data['name'], 'string');

aha. So this form: $this->request->getPost() escapes everything automatic?