<html>
<head>
<meta http-equiv="Content-Language" content="ja">
<meta http-equiv="Content-Type" content="text/html; charset=x-euc-jp">
<title>Vine Linux 2.6 Apache,PHP,PostgreSQL CSV file output test(2)!</title>
</head>
<body>
<div align="right">
<form>
<input type="button" value="close" onclick="javascript:window.close();">
</form>
</div>
<?php
// csvdata関数
// コード変換:EUC_JP ==> SJIS
// a,"b ==> "a,""b"
  function csvdata($in) {
     return "\"".str_replace("\"","\"\"",mb_convert_encoding($in,"SJIS","auto"))."\"";
  }

// table access
  $mysql="select * from mytable order by code";
  echo("SQL : ".$mysql."<br><br>");
  $mycon=pg_connect("dbname=template1 user=guest password=guest");
  $myrs=pg_query($mycon,$mysql);
  $mydir="tmp/";
  $myfilename="mytable2.csv";
  $myfp=fopen($mydir.$myfilename,"w");
  flock($myfp,2); //lock current csv file
  $CRLF="\r\n";    //SJIS改行データ
  $myrec="";
  $myrec=$myrec.csvdata("コード").",";
  $myrec=$myrec.csvdata("名称").",";
  $myrec=$myrec.csvdata("コメント").$CRLF;
  fputs($myfp,$myrec); //タイトル行出力

  $myrows=pg_num_rows($myrs);
  for ($i=0; $i<$myrows; $i++) {
    $mydata=pg_fetch_row($myrs,$i);
    $myrec="";
    for ($j=0; $j<count($mydata); $j++) {
       $myrec=$myrec.csvdata($mydata[$j]);
       if ($j<count($mydata)-1) {
           $myrec=$myrec.",";
       } else {
           $myrec=$myrec.$CRLF;
       }
    }
    fputs($myfp,$myrec);
  }
  pg_free_result($myrs); //free result_set memory
  pg_close($mycon);

  flock($myfp,3); //unlock current csv file
  fclose($myfp);

// CSVファイルへのリンク定義
  echo("<br><br>");
  echo("<a href=\"".$mydir.$myfilename."\">download CSV file</a>(SJIS)<br>");
?>
</body>
</html>