简体   繁体   中英

PHP MySQL Convert Multiple Columns into Multiple Rows

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 | email1@website.com | email2@website.com | email3@website.com

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 | email1@website.com
John | 555-555-5555 | email2@website.com
John | 555-555-5555 | email3@website.com

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM