Error when consulting with INNER JOIN

4

Everything works ok less when I pass the user id with the variable $ user_id.

It just fails me with the inner join, giving me the following error,

  

Catchable fatal error: Object of class User could not be converted to string in

Crud User contains,

public function usuarioCurso($id_usuario){
    var_dump($id_usuario);
    $db = BaseDatos::conectar();
    $listadoUsuario = [];

    $consultar = $db->prepare(
        "SELECT u.id_usuario, c.id_curso, m.id_mcurso FROM Usuario u
            INNER JOIN mapeo_curso m ON u.id_usuario = m.id_usuario
            INNER JOIN Curso c ON c.id_curso = m.id_curso
            WHERE $id_usuario = u.id_usuario
    ");

    $consultar->execute($id_usuario);

    $consultar->fetchAll();
}

Profile tab,

$usuario = $crud->obtenerUsuario($_GET['id_usuario']);
$listado = $crud->usuarioCurso($usuario['id_usuario']);
    
asked by sergibarca 17.04.2018 в 13:29
source

1 answer

4

If you want to filter by id_usuario the call the method should be done like this:

$listado = $crud->usuarioCurso($_GET['id_usuario']);

Then, the method must be modified:

  • your query is misspelled, since it would interpret that $id_usuario is the name of a column. The logical thing is that $id_usuario is the value to filter, in the query you must represent with a placeholder ? or :nombre if you want. And then, pass in the execute the value that the method received in parameter.
  • you make redundant use with fetchAll . That is, you tell him to do what he already did , since precisely what fetchAll does is return an array of the data set obtained.

The corrected code would look something like this:

public function usuarioCurso($id_usuario){
    $db = BaseDatos::conectar();

    $consultar = $db->prepare(
        "SELECT u.id_usuario, c.id_curso, m.id_mcurso FROM Usuario u
            INNER JOIN mapeo_curso m ON u.id_usuario = m.id_usuario
            INNER JOIN Curso c ON c.id_curso = m.id_curso
            WHERE u.id_usuario=?
    ");

    $consultar->execute(array($id_usuario));
    $listadoUsuario=$consultar->fetchAll();
    return $listadoUsuario;

}
    
answered by 17.04.2018 / 14:12
source