Why does Inner Join return repeated values?

Asked

Viewed 364 times

0

Good night,

I have a query to two tables where I want the second table to return all data with the id of table 1 but only returns me a table value when there are more than one with the same id. I need to get back all the data from the establishments table and return me the data that is associated with the establishment id of the establishments table.

Code

if($_REQUEST['valida'] != "ok"){
    if($result_alterar = $conexao->prepare("SELECT * FROM estabelecimentos 
                                            INNER JOIN categorias_estabelecimentos ON categorias_estabelecimentos.estabelecimento_id = estabelecimentos.id
                                            WHERE estabelecimentos.id = :id ")){
        $result_alterar->bindValue(':id', $_POST['id'], PDO::PARAM_INT);
        $result_alterar->execute();
        if($result_alterar->rowCount() >0 ){
            $row_alterar = $result_alterar->fetchAll(PDO::FETCH_ASSOC);
            $_REQUEST = $row_alterar; // O REQUEST ASSUME OS VALORES DO REGISTO, ASSIM EVITAMOS TER QUE CRIAR UM FORMULÁRIO INDEPENDENTE PARA AS EDIÇÕES

        }
    }
}

Table categories_establishments

CREATE TABLE IF NOT EXISTS `categorias_estabelecimentos` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`estabelecimento_id` int(11) NOT NULL,
`categoria_slug` varchar(250) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=311 ;

Table establishments

 CREATE TABLE IF NOT EXISTS `estabelecimentos` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `titulo` varchar(250) COLLATE utf8_unicode_ci NOT NULL,
  `slug` varchar(500) COLLATE utf8_unicode_ci NOT NULL,
  `link_facebook` varchar(250) COLLATE utf8_unicode_ci NOT NULL,
  `link_mapa` text COLLATE utf8_unicode_ci NOT NULL,
  `distritos` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `concelhos` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `morada` varchar(250) COLLATE utf8_unicode_ci NOT NULL,
  `contacto` varchar(250) COLLATE utf8_unicode_ci NOT NULL,
  `int_preco` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `link_site` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `introducao` text COLLATE utf8_unicode_ci NOT NULL,
  `servicos` varchar(500) COLLATE utf8_unicode_ci NOT NULL,
  `descricao` varchar(500) COLLATE utf8_unicode_ci NOT NULL,
  `keywords` varchar(500) COLLATE utf8_unicode_ci NOT NULL,
  `keywords_pesquisa` varchar(500) COLLATE utf8_unicode_ci NOT NULL,
  `google_verification` varchar(500) COLLATE utf8_unicode_ci NOT NULL,
  `activo` tinyint(1) NOT NULL,
  `pos` bigint(20) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=211 ;

Var Dump for $_REQUEST variable

http://pastebin.com/sJRswhvR

  • Only the code does not. Please post the structure of each table and its respective contents. Also post one print_r() and array_dump of $_REQUEST after setting it to $row_change

  • What happens to me now and that it lists all the respective data of the table categories_establishments with the same id of the table establishments but repeats the content I will put the structure

1 answer

1


You’re not just taking the first line?

$row_alterar = $result_alterar->fetch(PDO::FETCH_ASSOC);

What happens if you order it to return ALL lines (An Array will come in the case):

$row_alterar = $result_alterar->fetchAll(PDO::FETCH_ASSOC);

This returns all the values, the problem is that it may not solve in its use (From what I understand has a form involved).

In this case I imagine that the solution would be more in the line of linking an array with the categories to the single establishment. Correct?

Code suggestion:

if($_REQUEST['valida'] != "ok"){
    if($result_alterar = $conexao->prepare("SELECT * FROM estabelecimentos WHERE estabelecimentos.id = :id ")){
        $result_alterar->bindValue(':id', $_POST['id'], PDO::PARAM_INT);
        $result_alterar->execute();
        if($result_alterar->rowCount() >0 ){
            $row_alterar = $result_alterar->fetch(PDO::FETCH_ASSOC);

            // Puxamos as categorias relevantes para esse estabelecimento
            $result_categorias = $conexao->prepare("SELECT * FROM categorias_estabelecimentos WHERE estabelecimento_id = :id ")
            $result_categorias->bindValue(':id', $_POST['id'], PDO::PARAM_INT);
            $result_categorias->execute();

            // Colocamos a listagem com as categorias como um elemento do estabelecimento
            // Esse é um exemplo que não foi testado, não manjo tanto do seu ORM.
            $row_alterar['categorias_estabelecimentos'] = $result_categorias->fetchAll(PDO::FETCH_ASSOC);

            // Agora basicamente você tem um campo "categorias_estabelecimentos" que vai ter a listagem de categorias, em um único resultado com o estabelecimento que você precisa trabalhar.

            $_REQUEST = $row_alterar; // O REQUEST ASSUME OS VALORES DO REGISTO, ASSIM EVITAMOS TER QUE CRIAR UM FORMULÁRIO INDEPENDENTE PARA AS EDIÇÕES

        }
    }
}

Suggestion to print checkboxes (Not completely related but may be useful):

<?php foreach ($categorias_estabelecimentos as $cat) { ?>
    <input type="hidden" name="categorias_estabelecimentos[<?= $cat['id'] ?>]" value="0" />
    <input type="checkbox" name="categorias_estabelecimentos[<?= $cat['id'] ?>]" value="1" /> <?= $cat['categoria_slug'] ?>
<?php } ?>

Hidden is for, in the post, to have information that something has been unchecked. It’s the default used by frameworks like Rails and Angular. The suggestion is partly unrelated but I consider relevant because it deals with the peculiarities of dealing with arrays in editing screens, which is relevant to the issue in question.

  • Yes that had forgotten about fetchAll already put the problem and that now returns repeated values

  • The values in the table repeat the same data the number of data you have in the table categories

  • I updated it with a hint. I considered the result as an associative array, but possibly it is an object, and you might need something like $row_alterar->categorias_estabelecimentos to work.

  • Now returns well but does not assume the value in the variable request

  • Caesar, put it like you use that $_REQUEST then to see how to pass this data right. : D

  • use like this in the fields <?= $_REQUEST['descricao'] ?> for example

  • Caesar, in that case, $_REQUEST['categorias_estabelecimentos'] will be an array, and you can run it with something like <?php foreach ($categorias_estabelecimentos as $cat) { echo $cat['categoria_slug']; } ?>

  • Remember that it depends on $row_change being able to receive this new value. In some frameworks like Rails it depends on a configuration in the Model.

  • No use frameworks is programmed from root to nail

  • That way I can already get the data on the other side without problems now I’m having trouble checking the chekboxes

  • Caesar, I suggest a new question regarding checkboxes, the moderators are increasingly "picky". Put the link of the new question here and I help you with the greatest pleasure. : D

  • Here is the link http://answall.com/questions/56404/problema-com-checkbox

Show 7 more comments

Browser other questions tagged

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