Search code examples
phpsqlmysqliinner-join

Get foregin key value not id SQL


guys php beginner is here :)

i know my question has been asked a lot, but i read more than 20 answers & most of them not working with my query, and my query is simple but i don't know why didn't work with me :(,

i have 2 TABLE :

1- USERS : (id,username,country,status) primary key is id & foregin key is country

2- countries (country_id,country_en,country_code) primary key is country_id

when i insert data into countries table & inserting data into users everything FINE & CONNECTED to each other!

but when i came to query part here 's my problem : everything here is working! but the country output value is ID & i want it to be the name of it because the country_en has name values

$sql = "SELECT * FROM `users` 
        WHERE `users`.`status` = 'active' 
        ORDER BY RAND() LIMIT 10 ";

after i read many question's answers i tried to add UNION, LEFT JOIN, etc.. but still the same & i know the problem from my & i will learn from my mistakes final query that i tried to solve this issue

$sql = "SELECT * 
        FROM `users` WHERE `users`.`status` = 'active' 
        INNER JOIN `countries` ON `users`.`country` = `countries`.`country_en` 
        ORDER BY RAND() LIMIT 10 ";

could you guys help me with it :(


Solution

  • Thank to each of you for trying helping me,

    i would like to share with all of you the answer of my question with the best method to fetch the data of foregin key not the ID only, the method use "JOIN"

    minitauros says: JOIN works if tables have different column names. BELOW THE FINAL QUERY

    SELECT `users`.`id`, `users`.`username`, `users`.`country`, `users`.`status`, `countries`.`country_id`, `countries`.`country_en` FROM `users` JOIN `countries` ON `users`.`id` = `countries`.`country_id` WHERE `users`.`id` = 1
    

    In the ON part of the query you tell the query which column in the first table matches the which column in the second table.

    credit to minitauros

    The used SELECT statements have a different number of columns? 👍