Zoee
Zoee

Reputation: 9

Decrypt MYSQL data and create CSV

I am using this solution to encrypt and post some form data to my data base. On a separate page I now need to decrypt that data and save it all in to a CSV file with multiple rows.

My code decrypts fine (as when I echo $responses it prints all the correct data to the page) but I can't load it in to the CSV. This code creates a CSV but each field is in a random place and there are loads of odd characters. I've tried loads of variations of the below code (including loading it in to an array) with no luck.

$theresults = $wpdb->get_results( 
"
SELECT * 
FROM my_table
"
);

foreach ( $theresults as $result ) {

$iv = $result->iv;

$responses = openssl_decrypt($result->title,'AES-256-CBC',$encryption_key,0,$iv).",".
openssl_decrypt($result->fname,'AES-256-CBC',$encryption_key,0,$iv).",".
openssl_decrypt($result->lname,'AES-256-CBC',$encryption_key,0,$iv).",".
openssl_decrypt($result->address,'AES-256-CBC',$encryption_key,0,$iv).",".
openssl_decrypt($result->emailadd,'AES-256-CBC',$encryption_key,0,$iv).",".
openssl_decrypt($result->who,'AES-256-CBC',$encryption_key,0,$iv);

fputcsv($output, explode(',',$responses));

}

UPDATE

So I got this working by passing my data in to variables then creating my array like so:

$responses = array($title,$fname,$lname,$address,$age,$emailadd,$who);
fputcsv($output, $responses);

This inserts the correct rows in to a CSV file.

The issue I now have is the data is suffixed with odd characters such as diamond shapes, music symbols, lines, boxes with ? in them. Does anyone know what causes this?

Upvotes: 0

Views: 343

Answers (1)

Alex Howansky
Alex Howansky

Reputation: 53573

You're manually building a comma-separated string and then splitting on commas. If any of your fields actually contain commas, this will break since you're not escaping them. This will result in more fields than you expected, and they'll be in the wrong place. Instead, just drop the fields directly into an array and pass that array to fputcsv(), which will do the comma escaping for you.

$responses = [
    openssl_decrypt($result->title ... ),
    openssl_decrypt($result->fname ... ),
    ...
];
fputcsv($output, $responses);

Upvotes: 2

Related Questions