Association of categories in PHP and MYSQL [closed]

-4

I'm developing a site that has items, an item can have more than one category, how do I link those categories with that unique product?

    
asked by anonymous 15.09.2016 / 16:17

2 answers

-2

You should make a relationship from 1 to N, you should use this when a table needs to relate to multiple records from another table.

You will get the table item and the table category and another table that you can call from category_item. In it you will relate the other two tables.

Example category_item table:

categoria_item
- id_item
- id_categoria
    
15.09.2016 / 16:19
-2
  

As far as I can understand, you want to query the tables   related correct !? Following this reasoning you can try the   following:

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Cria uma conexão
$conn = new mysqli($servername, $username, $password, $dbname);
// Verifica a conexão
if ($conn->connect_error) {
    die("Erro de conexão: " . $conn->connect_error);
} 


// Monta o comando SQL para fazer a consulta
$sql = "SELECT i.nome, i.preco, c.nome as nomecategoria FROM item i INNER JOIN categoria c ON c.id = i.id_categoria";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // Saída dos dados a cada registro
    while($row = $result->fetch_assoc()) {
        echo "Item nome: " . $row["nome"]. " - preço: " . $row["preco"]. " - Categoria: " . $row["nomecategoria"]. "<br>";
    }
} else {
    echo "Sem resultados.";
}

// Encerra a conexão
$conn->close();
?>
  

I hope I have helped!   Home   Reference: link

    
15.09.2016 / 16:40