Jump to content

Copying from database..


grlayouts

Recommended Posts

This code will take you data from query and export it to a CSV formated file
[code=php:0]
<?
// Your defined Q string
// Used to get Data
    $result =  mysql_query("select * from tmptbl WHERE field1 = dvalue");
// Used to get field names   
    $result1 =  mysql_query("select * from tmptbl");
// Check to see if there were and natching records else exit with message
    if(!$result) {$exitcode++;
echo "No Records Found To Export<br>";
} else {
echo "Matching Records Being Exported<br>";
}
// if matching records were found export to a file (File name auto created based on date)
    if($exitcode == 0) {
// Define file name
    $filename = date("HismdY") . ".csv";
// Open file to write
    if (!$handle = fopen($filename, "wb")) {
// If error exit program    
        echo "Cannot open file " . $filename;
        exit();
    }
    $printcolnames = 1;
// loop thru qeury string to export data to CSV file
    while($row = mysql_fetch_array($result1))
    {
        $rowval = "";
        // ============ print column names ====================
        if($printcolnames == 1) {
            $data = "";
            $rowname = "";
// First Row is field names            
            for($i=0;$i<mysql_num_fields($result1);$i++) {
            $rowname .= mysql_field_name($result1, $i) . ",";
}
          $rowname = substr($rowname,0,-1) . "\r\n";
        if (!fwrite($handle, $rowname))
            {
                echo "Cannot write to file $filename";
              exit;
        }   
            $printcolnames = 0;
        }
        // ========= end print column names ===================
       
        // ========= print col values ========================
while($row = mysql_fetch_assoc($result)) {
// Create a row for every matching record
    foreach($row as $r) {
$r = str_replace(",", " ", $r);    
        $data .= $r . ",";
    }
    $data = substr($data,0,-1)."\r\n";
}
        if (!fwrite($handle, $data)){
//             echo "Cannot write to file $filename";
            exit;
        }   
        // ========= end print col values ===================
// Close File
    fclose($handle);
?>[/code]
Link to comment
https://forums.phpfreaks.com/topic/34146-copying-from-database/#findComment-161346
Share on other sites

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.