Jump to content

Exporting mysql to csv, can I add extra text to a field??


dropbop

Recommended Posts

I have been trying to figure this out for a while and I cant find anything that specificly shows how this is done..

 

I have a php script that exports certain fields from a mysql database table to a csv file. One of the fields in the table is 'products_image'.

 

From the code below the result is:

 

products_artist, products_title, products_label, products_image

Townes Van Zandt, Rain On A Conga Drum, Exile, image.jpg

 

What I would like to show is a full url of the image. Its not showing like that in the database so I would need to be able to add it to the script somehow so it outputs as below:

 

products_artist, products_title, products_label, products_image

Townes Van Zandt, Rain On A Conga Drum, Exile, http://www.domainname.com/images/image.jpg

 

<?php

  $conn = mysql_connect( 'localhost', 'user', 'pass' ) or die( mysql_error( ) );
  mysql_select_db( 'database_name', $conn ) or die( mysql_error( $conn ) );

  $query = sprintf( 'SELECT products_artist, products_title, products_label, products_image FROM products' );
  $result = mysql_query( $query, $conn ) or die( mysql_error( $conn ) );

  header( 'Content-Type: text/csv' );
  header( 'Content-Disposition: attachment;filename=export.csv' );

  $row = mysql_fetch_assoc( $result );
  if ( $row )
  {
    echocsv( array_keys( $row ) );
  }

  while ( $row )
  {
    echocsv( $row );
    $row = mysql_fetch_assoc( $result );
  }

  function echocsv( $fields )
  {
    $separator = '';
    foreach ( $fields as $field )
    {
      if ( preg_match( '/\\r|\\n|,|"/', $field ) )
      {
        $field = '"' . str_replace( '"', '""', $field ) . '"';
      }
      echo $separator . $field;
      $separator = ',';
    }
    echo "\r\n";
  }
?>

 

If anyone can point me in the right direction that would be great.

 

Many Thanks

 

DB

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.