Search code examples
mysqlpdoinnodbrelation

How relating two tables to show name row and not the id in mysql+pdo


I don't know how show the name of the row in table 2 instead of his id when show it results of table 1.

Let me explain:

I have this tables in innoDB:

- PACIENTES(table name).
    * id  (int)
    * nombre (varchar)
    * apellido (varchar)
    * pais (varchar)
    * departamento (varchar)
    * ciudad (varchar)

- lista_paises(table name).
    * id  (int)
    * opcion (varchar)

- lista_departamento(table name).
    * id_departamento  (int)
    * opcion (varchar)
    * relacion (int)-----relation with table lista_paises----

- MUNICIPIOS(table name).
    * id_municipio  (int)
    * id_departamento (int)-----relation with table lista_departamento----
    * municipio_nombre (varchar)

in table pacientes I have save the id of lista_paises, lista_departamento, municipios like

----id----nombre-----apellido-----pais----departamento----ciudad

  1    Juan    Perez     10      178        198

and I need to show in the page

 id   nombre  apellido     pais        departamento        ciudad

  1    Juan    Perez     El Salvador      Santa Ana        Santa Ana

I have this sentence(the other sentence with departamento is the same) but not show the real departamento or the real ciudad...always show only one departamento or municipio with id 1

<?
    $sql = "SELECT PACIENTES.ciudad, MUNICIPIOS.municipio_nombre 
    FROM PACIENTES INNER JOIN MUNICIPIOS 
    ON MUNICIPIOS.id_departamento = PACIENTES.ciudad";
    $stmt = $conn->prepare($sql);
    $stmt->execute(); 
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    $municipio_nombre = $row['municipio_nombre'];
?>

<td><? echo $municipio_nombre ?></td>

I'm sorry if my question is so long or not understand very well but to be honest I don't know how explain better this question... I hope you can help me with this


Solution

  • You have nombre_municipio in table and MUNICIPIOS.municipio_nombre in query.

    Also ON MUNICIPIOS.id_departamento = PACIENTES.ciudad is comparing varchar with int

    To Join MUNICIPIOS and PACIENTES you require to have field related to PACIENTES.id in MUNICIPIOStable eg (MUNICIPIOS.id_pacientes)

    $sql = "SELECT PACIENTES.ciudad, MUNICIPIOS.municipio_nombre 
        FROM PACIENTES 
        INNER JOIN MUNICIPIOS 
        ON  PACIENTES.id = MUNICIPIOS.id_pacientes";