PDA

View Full Version : export to cvs questions [php]



deletedUser2352352
January 10th, 2007, 06:58 AM
Hello all

I have created a page for my site that will allow me to export certain data to cvs file. Now this works and i can down load it off my server and all is fine there.

Here comes the question.

I have an array that i fill from my database and that works. But when i do pull that data it repeats the same information twice.

for example

1,1,firstname,firstname,lastname,lastname

and so on.

here is my code



// Create an instance of DbConnector and Validator
$connector = new DbConnector();
$result = $connector->query('SELECT ID,user,thegroup,firstname,surname,enabled,created ,logged_in,log_time,last_log FROM cmsusers ORDER BY ID');
while ($row = $connector->fetchArray($result)){
//create array of data from table
$usertrack[] = $row;
}


function makeCSV($data, $sep = ','){
if(!is_array($data)){
return 'no data';
}
$ret = '';
foreach($data as $record){
if(is_array($record)){
$ret .= join($sep, $record) . "\n";
}
}
return $ret;
}

echo makeCSV($usertrack);


Now the second part is this. I've seen it done and found a page on google that told me how to do this but i lost it and for the life of me can't find it again.

how can i get the title of each element from that array?

so if something is added in under firstname then the title of that part of the array is firstname.

If that doesn't make sense then please don't hesitate to ask.

bwh2
January 10th, 2007, 10:11 AM
hmm. i would first look into [d-php]array_keys[/d-php] for the column titles. i'm not sure about the duplicate info though.

deletedUser2352352
January 10th, 2007, 11:41 AM
Cheers.

Yeah its bugging why its duplicating it twice.

Thanks for that.

bwh2
January 10th, 2007, 12:14 PM
oh, i'm an idiot. here's what it is: basically, when you query using mysql_fetch_array (which your fetchArray method is probably doing), by default it will return both column names and auto generated array keys. so your row array actually looked like this:


Array
(
[ID] => 1
[0] => 1
[user] => uservalue
[1] => uservalue
[thegroup] => groupvalue
[2] => groupvalue
...
)
so you need to set your fetchArray to MYSQL_ASSOC so that you don't return the auto generated numeric keys. that leaves you with just this:


Array
(
[ID] => 1
[user] => uservalue
[thegroup] => groupvalue
...
)then you won't have more duplicate data. i figured this out by inserting a [d-php]print_r[/d-php] in the loop to see the array contents:


foreach($data as $record){
if(is_array($record)){
print_r( $record );
$ret .= join($sep, $record) . "\n";
}
}

deletedUser2352352
January 10th, 2007, 12:21 PM
Now i see wicked cheers for that mate.

Wicked