Please help me, I have issues inserting records

I'm trying to create a new record in the data base, but some fields can to be empty, when I insert a record empty in my data base appear with this : ' ' why ? I'm using postgresql.

    $cedula = $this->request->getPost("cedula","int");
    $nombre = $this->request->getPost("nombre",'striptags');
    $prueba = new Prueba();
    $prueba->nombre = $nombre;
    $prueba->cedula = $cedula;
        if ($prueba->create() == false) {

                        foreach ($prueba->getMessages() as $message) {
                            echo $message;

                        }
                        return false;

           }

in the database records are well

nombre/cedula/id
'';32432523;1
'';32432523;2
'';32432523;3
'';25235;4

sorry for my english, It's not very good.

Si no me di a entender, o si alguien habla español, necesito ayuda, cada vez que quiero registrar información en la base de datos y algún campo que no es obligatorio lo mando vacío desde el formulario, entonces se almacena con comillas simples '' cuando es de tipo string pero si es int me arroja este error : *Invalid text representation: 7 ERROR: invalid input syntax for integer: "" *

no sé que pasa!



34.7k
edited Jan '15

Hey

Are you sure get data corret here $nombre , you can debug here

[...]
    $nombre = $this->request->getPost("nombre",'striptags');

    var_dump($nombre);
    die;

[..]

Hey man, thanks for you answer. I know that nombre don't have nothing, is empty. I'm trying because I need to create a form that allow fields empty. but when I save the record whith a field empty then at the data base appear this: ''
when the data type is varying. but when the data type of the field is integer then appear this: Invalid text representation: 7 ERROR: invalid input syntax for integer: ""

sorry for my english. Hola amigo, gracias por tu respuesta, yo sé que nombre no tiene nada, está vacío. Estoy probando porque necesito crear un formulario que permita campos vacíos. Pero cuando yo guardo el registro con un campo vacío entonces en la base de datos aparece esto: '' cuando el tipo de dato es varying . pero cuando el tipo de dato es integer aparece esto: Invalid text representation: 7 ERROR: invalid input syntax for integer: ""

Maybe I didn't explained correctly, I want the possibility of null fields in my form. but I can't save records null.



34.7k

This mean you want validation before save for database, if is empty alter messages ? if is true check here http://docs.phalconphp.com/en/latest/reference/validation.html

yes, I have read about the validations, but I don't find it the solution.

in my application displays this exception

  • exception 'PDOException' with message 'SQLSTATE[22P02]: Invalid text representation: 7 ERROR: invalid input syntax for integer: ""' in /var/www/sigPACwt/app/controllers/ProyectoController.php:357 Stack trace: #0 [internal function]: PDOStatement->execute() #1 [internal function]: Phalcon\Db\Adapter\Pdo->executePrepared(Object(PDOStatement), Array, Array) #2 [internal function]: Phalcon\Db\Adapter\Pdo->execute('INSERT INTO "si...', Array, Array) #3 [internal function]: Phalcon\Db\Adapter->insert(Array, Array, Array, Array) #4 [internal function]: Phalcon\Mvc\Model->_doLowInsert(Object(Phalcon\Mvc\Model\MetaData\Memory), Object(Phalcon\Db\Adapter\Pdo\Postgresql), Array, 'id') #5 [internal function]: Phalcon\Mvc\Model->save() #6 /var/www/sigPACwt/app/controllers/ProyectoController.php(357): Phalcon\Mvc\Model->create() #7 [internal function]: ProyectoController->agregarAction() #8 [internal function]: Phalcon\Dispatcher->dispatch() #9 /var/www/sigPACwt/public/index.php(27): Phalcon\Mvc\Application->handle() #10 {main} SQLSTATE[25P02]: In failed sql transaction: 7 ERROR: current transaction is aborted, commands ignored until end of transaction block
  • *

The field that give issues can to be null, and is type integer



18.6k

when I insert a record empty in my data base appear with this : ' '

That will be because the DEFAULT value assigned in your field will be "". Try changing that default value and see if it changes also. And for the problem with the int type try to do a strval($nombre).

A ver, al insertar un valor nulo en una tabla, se supone que la BD le asignará por defecto un valor programado previamente. Si sólo has permitido nulos, pero no has especificado un valor concreto, aparecerá con comillas (""), en el caso de campos string. Prueba cambiándolo. Y el problema de los números diría que se resolvería haciendo strval($nombre).

edited Jan '15

This is how it can be done for SQLite, I've never used Postgres. Below example won't work in SQLite if nombre is a "not null" field, when it is, I'll get the expected error of something like "nombre is expected and cannot be empty". But the SQLite adapter won't add a pair of empty quotes to empty fields.

// $data is the post array.
$prueba->nombre = (!empty($data['nombre']) ? $data['nombre'] : null);

 or 

if (!empty($data['nombre'])) {
    $prueba->nombre = $data['nombre'];
}

Some other information, you might already know this, if you use a phalcon form sub class, you could add filters in addition to validators within the form subclass, if you have a field called nombre, then $nombre->setFilters([string | array]) or $nombre->addFilter("int") (edit: this doesn't convert value to zero if data isn't an integer) and then bind the post data to your entity like this $form->bind($this->request->getPost(), $prueba);. Your data will be filtered and model class populated with the filtered data. If you check the entity after binding, you get the filtered data.

There is a third parameter to $form->bind, (edit 2) The whitelist parameter lets you place in an array only the fields you want bound to your entity.