SQLSTATE error [23000] when trying to add a new item to my BD through my api

1

I am developing a API with slim framework 3 that connects to a local database. The problem is the following, when I try to insert a new element, it throws the following error {"error": {"text": SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'nombre' cannot be null} I share the code PHP , an image of my table and the error.

    $this->post('agregar', function(Request $request, Response $response){

    $nombre = $request->getParam('nombre');
    $sql = "INSERT INTO especialidad (nombre) VALUES(:nombre)"; 
    try{
        $db = new db();
        $db = $db->connect();
        $stmt = $db->prepare($sql);
        $stmt->bindParam(':nombre', $nombre);

        $stmt->execute(); 

        echo '{"notice": {"text": "Especialidad Agregada"}';

    } catch(PDOException $e){
        echo '{"error": {"text": '.$e->getMessage(). '}';
    }

});

    
asked by Germanccho 14.02.2018 в 15:48
source

1 answer

2

It is in the form with which you access the property name, as your endpoint is POST type, you must access the data like this:

$this->post('agregar', function(Request $request, Response $response){

  $param  = $request->getParseBody();
  $nombre = $param['nombre'];
  $sql    = "INSERT INTO especialidad (nombre) VALUES(:nombre)"; 

  try{
    $db = new db();
    $db = $db->connect();
    $stmt = $db->prepare($sql);
    $stmt->bindParam(':nombre', $nombre);

    $stmt->execute(); 

    echo '{"notice": {"text": "Especialidad Agregada"}';

  } catch(PDOException $e){
    echo '{"error": {"text": '.$e->getMessage(). '}';
  }

});
    
answered by 21.03.2018 в 01:18