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

可紊 提交于 2019-12-08 08:57:35

问题


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


回答1:


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";


来源:https://stackoverflow.com/questions/17262938/how-relating-two-tables-to-show-name-row-and-not-the-id-in-mysqlpdo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!