3

我正在将数据导出到一个.csv文件中,它运行良好,但我有一个小问题。我从一个表中获取namegender,但对于我保存id在我的数据库中的性别(即1 = Male,,2 = Female)。我下面的代码给了我性别的 id,我该如何解决?男性返回 1,女性返回 2:

$rows = mysql_query("SELECT `name`, `gender` FROM TABLE");

while ($row = mysql_fetch_assoc($rows)) {
    fputcsv($output, $row);
}
4

3 回答 3

6

尝试这个 :

$rows = mysql_query("SELECT `name`, `gender` FROM TABLE");

while ($row = mysql_fetch_assoc($rows)) {

    if($row['gender'] == 1) {
        $row['gender'] = 'Male'; 
    } else {
        $row['gender'] = 'Female'; 
    }

    // Or ternary condition
    // $row['gender'] = ($row['gender'] == 1 ? 'Male' : 'Female');

    fputcsv($output, $row);
}
于 2014-03-07T13:55:20.550 回答
2
<?php

    $db_record = 'yourRecod';
    // optional where query
    $where = 'WHERE 1 ORDER BY 1';
    // filename for export
    $csv_fileName = 'db_export_'.$db_record.'_'.date('Y-m-d').'.csv';

    // database variables
    $hostname = "localhost";
    $user = "yourUserName";
    $password = "yourPassword";
    $database = "yourDataBase";

    // Database connecten voor alle services
    mysql_connect($hostname, $user, $password)
    or die('Could not connect: ' . mysql_error());

    mysql_select_db($database)
    or die ('Could not select database ' . mysql_error());

    $csv_export = '';

    $query = mysql_query("SELECT * FROM ".$db_record." ".$where);
    $field = mysql_num_fields($query);

    // create line with field names
    for($i = 0; $i < $field; $i++) {
      $csv_export.= mysql_field_name($query,$i).';';
    }
    $csv_export.= '';
    while($row = mysql_fetch_array($query)) {
      // create line with field values
      for($i = 0; $i < $field; $i++) {
        $csv_export.= '"'.$row[mysql_field_name($query,$i)].'";';
      } 
      $csv_export.= ''; 
    }

    // Export the data and prompt a csv file for download
    header("Content-type: text/x-csv");
    header("Content-Disposition: attachment; filename=".$csv_fileName."");
    echo($csv_export);
?>

我给你完整的示例代码,我使用 PHP 将 MySql 数据导出到 .CSV

于 2014-03-07T14:03:55.157 回答
2

在您的 SQL 中使用IF statement来最小化 PHP 逻辑:

SELECT `name`, IF(gender=1,'Male','Female') as 'gender' FROM TABLE
于 2014-08-12T20:36:23.177 回答