PHP - CSV export help

Discussion in 'PHP' started by sam20e, Sep 4, 2012.

  1. #1
    Hi

    Pls refer bellow mentioned code.. this code will prompt 2 hyperlinks when we click that it will export the result to CSV file..

    My problem is i can set the conditions in where clause for 2 links individually.. but i need to select the different table columns.. example for these 2 csv export links, i can set the condition in

    'where'=>"WHERE id=1",
    PHP:
    But i got only 1 definition :

    $sql_query = "select * from $table ".$where;
    PHP:
    can anyone advise me how can i have different select query for these 2 links individually? so i can select any column from tbl1 or tbl2

    for example i need something like this :

    
    $sql_query1 = "select id,name from $table ".$where;
    $sql_query2 = "select firstname,lastname from $table ".$where;
    $sql_query3= "select location from $table ".$where;
    
    PHP:
    This is the full code :

    <?php
    function exportMysqlToCsv($table,$where = '',$filename = 'Report.csv')
    {
        $csv_terminated = "\n";
        $csv_separator = ",";
        $csv_enclosed = '"';
        $csv_escaped = "\\";
        $sql_query = "select * from $table ".$where;
     
        // Gets the data from the database
        $result = mysql_query($sql_query);
        $fields_cnt = mysql_num_fields($result);
     
     
        $schema_insert = '';
     
        for ($i = 0; $i < $fields_cnt; $i++)
        {
            $l = $csv_enclosed . str_replace($csv_enclosed, $csv_escaped . $csv_enclosed,
                stripslashes(mysql_field_name($result, $i))) . $csv_enclosed;
            $schema_insert .= $l;
            $schema_insert .= $csv_separator;
        } // end for
     
        $out = trim(substr($schema_insert, 0, -1));
        $out .= $csv_terminated;
     
        // Format the data
        while ($row = mysql_fetch_array($result))
        {
            $schema_insert = '';
            for ($j = 0; $j < $fields_cnt; $j++)
            {
                if ($row[$j] == '0' || $row[$j] != '')
                {
     
                    if ($csv_enclosed == '')
                    {
                        $schema_insert .= $row[$j];
                    } else
                    {
                        $schema_insert .= $csv_enclosed . 
    
    	
    
    	
    
    	
    
    	
    
    	
    
    str_replace($csv_enclosed, $csv_escaped . $csv_enclosed, $row[$j]) . $csv_enclosed;
                    }
                } else
                {
                    $schema_insert .= '';
                }
     
                if ($j < $fields_cnt - 1)
                {
                    $schema_insert .= $csv_separator;
                }
            } // end for
     
            $out .= $schema_insert;
            $out .= $csv_terminated;
        } // end while
     
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Content-Length: " . strlen($out));
        // Output to browser with appropriate mime type, you choose ;)
        header("Content-type: text/x-csv");
        //header("Content-type: text/csv");
        //header("Content-type: application/csv");
        header("Content-Disposition: attachment; filename=$filename");
        echo $out;
        exit;
     
    }
    // please assign more table with assoiciated name.
    $lst_csv_req = array(
        'All Employees Records'=>
            array(
                'table'=>'tbl1', 
                'where'=>"WHERE id=1",
                'db'=>'testdb'),
         'All Employees Records2'=>
            array(
                'table'=>'tbl2', 
                'where'=>"WHERE id=1",
                'db'=>'testdb')
        );
    
    
    if(isset($_GET['action'])):
    
    $host = 'localhost'; // MYSQL database host adress
    $db = 'testdb'; // MYSQL database name
    $user = 'testdb'; // Mysql Datbase user
    $pass = 'testdb'; // Mysql Datbase password
     
    // Connect to the database
    $link = mysql_connect($host, $user, $pass);
    //mysql_select_db($db);
     
     if(array_key_exists ( $_GET['action'] , $lst_csv_req)) {
        $req_arr = $lst_csv_req[$_GET['action']];
        if(!isset($req_arr['table']) || trim($req_arr['table']) == '')
        {
            echo 'Please check array. table name not entered';
            exit;
        }
        if(!isset($req_arr['db']) || trim($req_arr['db']) == '')
        {
            echo 'Please check array. DB name not entered';
            exit;
        }    
       // $where = ' '.@$req_arr['table'].' ';
    
    	
    
      $where = ' '.@$req_arr['where'].' ';
     mysql_select_db($req_arr['db']);
        $table= $req_arr['table']; // this is the tablename that you want to export to csv from mysql.
    
        exportMysqlToCsv($table, $where);
     }
     else
     {
         echo "requested report does not exist.";
     }
     
    endif;
    
    // generate link:
    echo "<strong>Report download link:</strong><br />
         --------------------------------------------<br />";
    foreach($lst_csv_req as $key=>$vale):
        $link = $_SERVER['PHP_SELF']."?action={$key}"; 
        echo "<a href='$link '>{$key} - [ Download Report ]<br /></a>";
    endforeach;
    ?>
    
    
    
    
    PHP:

    Thanks
     
    sam20e, Sep 4, 2012 IP
  2. greyinfotech

    greyinfotech Peon

    Messages:
    14
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #2
    can't you decide what column you select like you decide where clause.

    put columns list in variable as

    
    
    $columns = "firstname,lastname";
    $sql_query1 = "select $columns from $table ".$where;
    
    
    Code (markup):
    now depends on your requirement you can set any column list in $columns variable
     
    greyinfotech, Sep 18, 2012 IP