简体   繁体   中英

PHP: exporting mysql database into CSV based on 2 columns?

I have a users table in mysql database and each user has a referral_code column and a referral_code_used column.

The referral_code holds the users referral code that they can share with others.

The referral_code_used holds the referral code that the user's received from another user and they have entered during the signup.

Example:

user   referral_code    referral_code_used        email

A         TW89                                email@email.com
---------------------------------------------------------------
B         TW66               TW89            email2@email.com   

In the example above, the user B has used the user A referral_code .

Now, what i need to do is to export this data into a CSV file and the CSV file should look like this (sort of):

referrer                   referred         

email@email.com         email2@email.com 

that's it.

so far I can export the entire mysql as CSV file using the following code but I can't figure out how to do what I am trying to do and I don't know if it is possible:

<?php

    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=data.csv');

    $output = fopen('php://output', 'w');

    $rows = mysqli_query($db, 'SELECT * FROM `users`');

    while ($row = mysqli_fetch_assoc($rows)) {


      fputcsv($output, $row);
    }
    fclose($output);
    mysqli_close($db_conx);
    exit();

?>

Any help would be greatly appreciated.

Thanks in advance.

EDIT:

I tried this and this will generate an empty CSV file:

<?php

    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=data.csv');

    $output = fopen('php://output', 'w');

    $rows = mysqli_query($db_conx, 'SELECT u.email as referrer, ref.email as referred from users u INNER JOIN users ref on u.ref_code=ref.ref_code_used');

    while ($row = mysqli_fetch_assoc($rows)) {


      fputcsv($output, $row);
    }
    fclose($output);
    mysqli_close($db_conx);
    exit();

?>

and I don't see any errors at all!

This should work - the concept you're looking for is inner-joining the table to itself in order to match different rows to each other, based on the referral codes:

select 
  A.email as 'referrer', 
  B.email as 'referred'
from 
  users A
  inner join users B
    on A.referral_code = B.referral_code_used

This looks like a case where you have to make a join on the same table. I imagine something like this:

Select u.email as referrer, ref.email as referred from users u 
INNER JOIN users ref on u.referral_code=ref.referral_code_used

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