Tenho duas tabelas relacionadas em que cada pessoa pode ter 1 ou mais telefones.
Como faço pra exibir todos os telefones para cada pessoa?
Da forma como fiz mostra o nome repetido para cada telefone.
Está exibindo assim:
Nome | Telefones
fulano | 12345
fulano | 54321
Só que eu quero exibir o nome da pessoa e a lista de telefones da pessoa, assim:
Nome | Telefones
fulano | 12345
54321
Como faço isso?
Se alguém puder me ajudar ficarei grato.
CREATE TABLE IF NOT EXISTS `pessoa` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`nome` varchar(50) DEFAULT NULL,
`email` varchar(50) DEFAULT NULL,
`cpf` varchar(20) DEFAULT NULL,
PRIMARY KEY (`id`),
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=24;
CREATE TABLE IF NOT EXISTS `telefone` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`numero` varchar(14) DEFAULT NULL,
`id_pessoa` int(11) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `telefone_pessoa` (`id_pessoa`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=19 ;
<?php
$statement = $pdo->prepare("SELECT telefone.numero, pessoa.* FROM telefone INNER JOIN pessoa ON (pessoa.id = telefone.id_pessoa);");
$statement->execute();
$usuarios = $statement->fetchAll(PDO::FETCH_OBJ);
?>
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>Nome</th>
<th>Telefone</th>
</tr>
</thead>
<tbody>
<?php foreach ($usuarios as $usuario): ?>
<tr>
<td><?php echo $usuario->nome; ?></td>
<td><?php echo $usuario->numero; ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>