0

I have 2 tables person and country. Table person has 3 columns id_person, name_person and id_country. country has 2 columns id_country and name_country.

I want to show "name_person" and "name_country", just the name of column, not record. How can I get this ?

4
  • Please have a look at this answer. Commented Jun 30, 2016 at 7:24
  • 1
    It would be helpful to understand what you're trying to achieve. Why do you want to get the column names, if you already know them? Commented Jun 30, 2016 at 7:30
  • i want to get the name of column to create a string from it. then merge it with the record of table. Finally I have only one string. sorry for my bad english sir :) Commented Jun 30, 2016 at 7:40
  • What is the query you are trying to do? Commented Jun 30, 2016 at 9:00

3 Answers 3

5

You can access table columns in MySQL's information schema database:

SELECT `COLUMN_NAME` 
FROM `INFORMATION_SCHEMA`.`COLUMNS` 
WHERE `TABLE_NAME` IN ('country', 'person')
    AND `COLUMN_NAME` LIKE 'name_%';
Sign up to request clarification or add additional context in comments.

Comments

2

This should do it:

$result = $db->query('SELECT p.name_person, c.name_country FROM person AS p LEFT JOIN country as c ON (p.id_country=c.id_country)');
$fields = array_keys($result->fetch(PDO::FETCH_ASSOC));

If you want to get the data an not only the columns names, just remove the array_keys.

$fields = $result->fetch(PDO::FETCH_ASSOC);

2 Comments

that's show the records. I want to show the name of column
The first on using array_keys should only print the column names.
0

You can use

    $result = $db->query('SELECT person.name_person, country.name_country FROM person LEFT JOIN country ON (person.id_country=country.id_country)');

    print_r(array_keys($result));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.