Read data in an SQL with columns of equal names in different tables

Asked

Viewed 799 times

1

I need to recover data from 2 tables. My SQL presented below works perfectly. The problem is that I made a foreach to recover data from the second table by field ID that is conflicting with the first table since the two have the field ID.

SQL

$sql = "SELECT tb_faqs.*, tb_paginas.* 
FROM (tb_faqs INNER JOIN tb_paginas) 
WHERE tb_faqs.ID = '$id' 
AND tb_faqs.id_pagina = tb_paginas.ID";

$query = $pdo->query($sql);
$pagina = $query->fetch();

This SQL search all the necessary data for the two tables but I need to do a foreach in the second table to mount a select from that query. This is the foreach:

foreach ($pdo->query($sql) as $pagina) {
     echo '<option value="'.$pagina['ID'].'" '.(($pagina['id_pagina'] == $pagina['ID']) ? 'selected="selected"' : "").'>'.$pagina['pagina'].'</option>';
}

Question: When two tables have the same column name, how to specify which table we want to refer to that column?

1 answer

2


Change your SQL to:

$sql = "SELECT tb_faqs.*, tb_fags.id as id_fag, tb_paginas.*, tb_paginas.id as id_pagina 
FROM (tb_faqs INNER JOIN tb_paginas) 
WHERE tb_faqs.ID = '$id' 
AND tb_faqs.id_pagina = tb_paginas.ID";

And at Foreach time() do: echo $id_fag, echo $id_pagina... There is no need to be exactly these names, if give conflict, change, that it creates an analysis(s) for each ID.

  • ALIAS echo is something like $faqs['idpag'] within the foreach() ...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.