List all data with the same id

Asked

Viewed 917 times

0

I have the following problem: I have a table called pedido. In this table I get data from two other tables:

tabela pedido

I would like to make a list only of products that have the same id_venda. In my code only appears the first item added with equal id:

    <?php

$perfil1=mysql_query("SELECT * FROM pedido WHERE id_venda='$id'");

$lista=list($id, $produtosb , $idvenda)=mysql_fetch_row($perfil1);


$prod = "SELECT * FROM produtos WHERE id_produto=". $lista[1];
$query = mysql_query($prod);
$b=mysql_fetch_array($query);
$prod = $b ['produtos'];

?>

<input type="text" name="id" style="width: 450px" readonly="true"  value="<?php echo $prod; ?>"><br>

I tried using Loop while, but it returns all table data. Which repeat loop should I use?

  • select * from pedidos inner join produtos on produtos = id_produto where id_venda= $id Just pick the result and list using while.

  • 1

    If I were you I would use much more practical and safe PDO to work with database. This mysql_* function has become obsolete, since php 7 it will no longer exist!

1 answer

3


Come on...

Assuming that the column produtos be the sale product id in the table pedidos, and with id_venda defined, we solve the problem with a query only:

Supposing that your column produtos has been:

id | nome

Behold the select:

$SQL = "SELECT * FROM produtos WHERE id_produto in (SELECT produtos FROM pedido WHERE id_venda='$id')";
$result = mysql_query($SQL);

while ($db_field = mysql_fetch_assoc($result) ) {

print $db_field['ID'] . "<BR>";
print $db_field['nome'] . "<BR>";

}

EDIT:

Use with Join:

$SQL = "SELECT * FROM pedido inner join produtos on produtos = id_produto where id_venda='$id'";
  • 2

    Inner Join would not be better than subquerys?

  • Opa amigo vlw by help I made some changes and gave right to min , very obg ;)

  • Boy.... there is a severe discussion by the world about this.... rs. I always used Ner Nino... from a while back, I started using Nino in the Where... and sometimes Queries.. I think that in the end, whatever is best visually prevails ... As is only my opinion, I put an example using the inner join ;)

  • 1

    No problem Marllon :-) There is only one mistake in the query of Join, is "jointing" products with itself, I think would be with the table Pedido.

  • 1

    truth! haha edited there! thanks, @Diegofelipe

  • This looks like something to talk about Outer Join, not Inner.

Show 1 more comment

Browser other questions tagged

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