Notice: Trying to get property of non-object

2

I'm having the following error:

Notice: Trying to get property 'idDia' of non-object in C:\wamp64\www\backend-trabajo-final\profesionales\select-profesionales-para-posible-servicio.php on line 26 (So, with each of the properties I try to extract from the variable $ obj that is in the .php) and finally I catch an exception:

Excepción capturada: SQLSTATE[HY093]: Invalid parameter number

I am using Postman to do the tests, I use the POST method and in the Body I use raw with the JSON type (application / json) and I send the following data:

{
    "idDia" : 4,
    "fecha" : '2018-09-20',
    "hora" : '09:00:00',
    "idOficio" : 1,
    "idArea" : 1
}

The .php file is this:

<?php

    //DEFINE LOS PARAMETROS DE CONEXION
    $host = 'localhost';
    $usuarioBD = 'root';
    $passBD = '';
    $bd = 'tf';
    $codif = 'utf8';

    //CONFIGURA LOS PARAMETROS
    $url = "mysql:host=" . $host . ";port=3306;dbname=" . $bd . ";charset=" . $codif;
    $opt = array(
                PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
                PDO::ATTR_EMULATE_PREPARES   => false,
                );

    //CREA LA INSTANCIA DE PDO (CONECTA A LA BD)
    $pdo = new PDO($url, $usuarioBD, $passBD, $opt);

    //RECIBE LOS DATOS DEL FRONTEND EN FORMATO JSON
    $json = file_get_contents('php://input');
    //LOS DECODIFICA
    $obj = json_decode($json);
    //EXTRAE LOS DATOS RECIBIDOS y ACÁ ABAJO DONDE ME TIRA EL ERROR
    $idDia = $obj->idDia;
    $fecha = $obj->fecha;
    $hora = $obj->hora;
    $idOficio = $obj->idOficio; 
    $idArea = $obj->idArea;

    var_dump($json);
    var_dump($obj);

    try {

        //BUSCA LOS PROFESIONALES QUE NO PUEDEN
        $sql1 = "SELECT profesionales.idProfesional, usuarios.idUsuario, usuarios.nombre, usuarios.apellido from profesionales, usuarios,
    (select T.idProfesional, servicios.hora
    from  detallesservicios inner join servicios 
    on detallesservicios.idServicio = servicios.idServicio inner join (select profesionales.idProfesional from horarios, profesionales where
    horarios.idDia = :idDia
    and profesionales.idEstadoP = 1
    and horarios.desde < :hora_i
    and horarios.hasta > :hora_j
    and horarios.idArea = :idArea
    and profesionales.idOficio = :idOficio
    group by profesionales.idProfesional) as T on
    T.idProfesional = detallesservicios.idProfesional
    where servicios.fecha = :fecha and not(timediff(servicios.hora, :hora_k) > '00:57:00')
    group by servicios.idServicio order by T.idProfesional) as TT
    where profesionales.idProfesional <> TT.idProfesional
    and profesionales.idUsuario = usuarios.idUsuario
    group by profesionales.idProfesional";
        $stmt1 = $pdo->prepare($sql1);
        $stmt1->bindParam(':idOficio', $idOficio);
        $stmt1->bindParam(':hora_i', $hora);
        $stmt1->bindParam(':hora_j', $hora);
        $stmt1->bindParam(':hora_k', $hora);
        $stmt1->bindParam(':fecha', $fecha);
        $stmt1->bindParam(':idDia', $idDia);
        $stmt1->bindParam(':idArea', $idArea);
        $stmt1->execute();
        $filasDevuelta = $stmt1->rowCount();

        //SI LO ENCUENTRA, SINO
        if(($filasDevuelta) > (0)) {

            while($fila  = $stmt1->fetch(PDO::FETCH_OBJ))
            {
                // Asigna cada fila de datos a la matriz asociativa
                $datosNoUsuarios[] = $fila;
            }

            // Devuelve los datos como JSON
            console.log("Datos noUsuarios: " . $datosNoUsuarios);
            echo json_encode($datosNoUsuarios);

        } else {

            //echo 'No existe el usuario.';
            echo '{"error":{"texto":"No existen profesionales para el servicio solicitado."}}';

        }

    } catch(PDOException $e) {

        echo 'Excepción capturada: '.  $e->getMessage();

    }

As you can see, $obj takes the decoded value of the input $json , but I can not extract the data with the properties below (for example: $idDia = $obj->idDia ) and so on with all the other properties of $obj .

In the var_dump() the following values come to me:

C:\para-posible-servicio.php:32:string '{   "idDia" : 4,
    "fecha" : '2018-09-20',
    "hora" : '09:00:00',
    "idOficio" : 1,
    "idArea" : 1 }' (length=94)
C:\para-posible-servicio.php:33:null

That is, in $json data comes, but it does not take $obj .

The weird thing is that the code copies it from other files that I did and that work well. It may be that I misdirected JSON data but I checked them several times and there is no case.

    
asked by GADGustavo67 24.09.2018 в 15:38
source

1 answer

2

The problem is that your json is not valid , values with single quotes like these are not supported:

"fecha" : '2018-09-20', 
"hora" : '09:00:00',

so this json does not validate :

{
    "idDia" : 4,
    "fecha" : '2018-09-20',
    "hora" : '09:00:00',
    "idOficio" : 1,
    "idArea" : 1
}
  

Error: Parse error on line 3: ... dDia ": 4," date ":   '2018-09-20', "time   ---------------------- ^ Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '[ ', got' undefined '

You must therefore generate a valid json :

{
    "idDia": 4,
    "fecha": "2018-09-20",
    "hora": "09:00:00",
    "idOficio": 1,
    "idArea": 1
}
  

Valid JSON

Note that in the date and time keys the values are used using double quotes " .

From there, the rest of the code should work.

    
answered by 24.09.2018 / 16:26
source