Home » Php » php – Fetch from 2 tables by inner join

php – Fetch from 2 tables by inner join

Posted by: admin February 25, 2020 Leave a comment

Questions:

Hi i want to mysqli fetch data from db but if i use join and in Categories i have ‘name’ and in Products same. While im using data like:

$sql = "SELECT * FROM Products INNER JOIN Categories ON Products.id_category = Categories.id";
        $result = $connection->query($sql);

        if ($result->num_rows > 0) {
            // output data of each row
            while($row = $result->fetch_assoc()) {
                echo '$row["name"]'

my site shows Categories.name how can i take Products name

Other query or something?

How to&Answers:

Your intuition was correct about needing to change the query. You need to specify which fields you want to select and give any fields that have duplicate names a unique name.

SELECT p.id, p.name as 'product_name', c.name as 'category_name' 
FROM Products p
INNER JOIN Categories c ON p.id_category = c.id