0

So I have a database table that is structured something like this...

NAME | PHONE | EMAIL1 | EMAIL2 | EMAIL3

Those would be my columns, imagine this is a row in that database..

John | 555-555-5555 | [email protected] | [email protected] | [email protected]

I need to be able to dump these entries to a CSV which I have the code for working already BUT the format is the issue.

I need each email to be displayed on a single row with the corresponding name and number, in the following format...

John | 555-555-5555 | [email protected]
John | 555-555-5555 | [email protected]
John | 555-555-5555 | [email protected]

I need to retrieve thousands of rows and display them this way, is there some way using a PHP while loop I can display the rows from my database table in this format? Any help is greatly appreciated.

4
  • Yes, there is a way. But I'm afraid it's on you to do the first step and actually try something. (just loop through the rows and add 3 items per row to an array. And maybe test if you have something in each column) Commented May 18, 2018 at 22:55
  • 2
    Why do you have your table like this in the first place? What if someone has more than 3 emails? You should normalize the data by putting emails into a separate table with 1 row per email. Commented May 18, 2018 at 23:27
  • @Barmar As an aside, I know no one in that enviable position. Commented May 19, 2018 at 9:30
  • 1
    @Strawberry True dat. I've had the luxury of normalizing a schema at my job just once, because the application was being replaced and I could do it right from scratch. But like telling people not to use mysql_* functions, we're legally obligated to comment about it. :) Commented May 19, 2018 at 12:15

1 Answer 1

1

This process is called unpivoting.
And is most commonly done with UNION ALL within MySQL.

SELECT 
   NAME
 , PHONE
 , EMAIL1 
FROM 
 table

UNION ALL 

SELECT 
   NAME
 , PHONE
 , EMAIL2 
FROM 
 table

UNION ALL 

SELECT 
   NAME
 , PHONE
 , EMAIL3 
FROM 
 table
Sign up to request clarification or add additional context in comments.

1 Comment

We could also omit rows that have NULL values for email column by adding a WHERE clause to each SELECT. To apply an ORDER BY to the entire set, we can enclose each SELECT in parens, and then add an ORDER BY clause after the last closing paren. +10.

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.