S
S
Sofard2020-10-04 00:41:17
PHP
Sofard, 2020-10-04 00:41:17

When selecting two tables from the database with one query, duplicates are obtained in the output. What could be the problem?

Hello! When I select two tables from the database, it turns out that I have duplicate products displayed. What I understood is the number of duplicates depends on how many rows there are in the other table.
There is a table `table_products` and `cart` . Each row, when output from the `table_products` table , is output as many times as there are rows in the `cart` table .
Example: `table_products` has 2 rows, NAME_1 and NAME_2 . There are 4 lines in `cart` .
OUTPUT: NAME_1 NAME_1 NAME_1 NAME_1 NAME_2 NAME_2 NAME_2 NAME_2

Here is my query:

$query = $pdo->query("SELECT * FROM table_products, cart");
while ($row = $query->fetch(PDO::FETCH_OBJ)) {
<div class="product" id="<?php echo"$row->products_id"; ?>">
<img src="<?php echo"$row->image"; ?>" class="image-product">
<div class="title-prod"><h2><a href="product.php?id=<?php echo "$row->products_id"; ?>"><?php echo "$row->title"; ?></a></h2></div>
}

___
Thank you all! Everyone who answered gave me the right solution to my problem, thank you so much!
PS: My query is now: SELECT * FROM table_products LEFT JOIN cart ON table_products.products_id = cart.cart_id_products

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Rsa97, 2020-10-04
@Sofard

You are sampling the Cartesian product of two tables. So at the output you have all possible pairs of rows from the first and second tables.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question