PHP выбор оператора из MySql в Excel. Форматирование даты в ГГГГММДД - PullRequest
0 голосов
/ 18 января 2010

Примечание: в базе данных MySql "dob" - это varchar, и в этом формате: мм / дд / гггг

Дата рождения, Дата вступления в силу Cvrg и Дата истечения срока действия Cvrg должны быть изменены с мм / дд / гггг на ггггммдд, когда они поступают в Excel. Пожалуйста, смотрите код ниже:

    <?php 
    if($qry == "ok"){
     // get db connection
     include("connection string goes here");

     $select = "SELECT 'A' AS 'Transaction Type', policyno AS 'UHCSR Policy No', school                 AS 'Campus Location Description', Code AS 'Campus Location Number', '' AS 'Date Received by         UHCSR', '' AS 'Date Stamped By School', '' AS 'Social Security Number', SSN AS 'StudentID Number', 
      lname AS 'LastName', fname AS 'FirstName', mi AS 'Middle Initial', dob AS 'Date of Birth', gender AS 'Gender',
      concat( concat(address1, ' '), address2) AS '(Mailing) Address Ln 1','' AS '(Mailing) Address Ln 2',city AS '(Mailing) City', state AS '(Mailing) State', zipcode AS '(Mailing) ZipCode', '' AS '(Mailing) ZipCode Suffix', 
      '' AS '(Permanent) Address Ln 1', '' AS '(Permanent) Address Ln 2', '' AS '(Permanent) City', '' AS '(Permanent) State', '' AS '(Permanent) ZipCode', '' AS '(Permanent) ZipCode Suffix', email AS 'Email Address', replace(phone, '-', '') AS 'Telephone Number', 'ITL' AS 'Insured Category Code', '' AS 'Insured Type Code', 'A' AS 'Insured (Row)ID Code', period AS 'Period Code', semester AS 'Cvrg Period Description',
      trim(left(coveragedate, locate('-', coveragedate)-1)) AS 'Cvrg Effective Date',
      trim(replace(right(coveragedate, locate('-', coveragedate)+0),'-','')) AS 'Cvrg          Expiration Date',
      noadfee AS 'Premium Amount', quantity AS 'Coverage Period Quantity', '' AS 'Primary Insured SSN', SSN AS 'Primary Insured Student ID', '' AS 'Organization Name',  '' AS 'Organization Number', '' AS 'Dependent Coverage Code',  '' AS 'Check Number',  '' AS 'Credit Card Number',  '' AS 'Credit Card Expiration Month',  '' AS 'Credit Card Expiration Year', tedfee AS 'Amount Paid', paytype AS 'Pay Type'
     FROM intenrollment
     WHERE confirm = 'Y' and amountpaid != '0' and (policyno LIKE '%200473-%' OR policyno LIKE '%2060-%'  OR policyno LIKE '%202377-%' or policyno='')";

      if ( $smon != "None" and $sday != "None" and $syear != "None" and $emon != "None" and $eday != "None" and $eyear != "None" )
      {
       $startdate = strtotime("$smon $sday, $syear");
       $enddate = strtotime("$emon $eday, $eyear");
       $select .= "AND applydate BETWEEN $startdate AND $enddate ";
      } elseif ( $smon != "None" and $sday != "None" and $syear != "None" ) {
       $startdate = strtotime("$smon $sday, $syear");
       $select .= "AND applydate > $startdate ";
      } elseif ( $emon != "None" and $eday != "None" and $eyear != "None" ) {
       $enddate = strtotime("$emon $eday, $eyear");
       $select .= "AND applydate < $enddate ";
      }

      $select .= "ORDER BY school ASC, lname ASC";

      // run query
      $export = mysql_query($select) or die(mysql_error());
      $fields = mysql_num_fields($export);

      // get field info for headers
      $header = '';
      for ( $i = 0; $i < $fields; $i++ )
      {
       $header .= mysql_field_name($export, $i) . "\t";
      }

      // extract data and convert into excel readable format
      $data = '';
      while ( $row = mysql_fetch_row($export))
      {
       $line = '';
       foreach ( $row as $value )
       {
        if ( ( !isset($value) ) OR ( $value == "" ) )
        {
         $value = "\t";
        } 
        else 
        {    
         $value = str_replace('"', '""', $value);
        $value = '="' . $value . '"' . "\t";
     //        ^
     //        Added an equal sign
        }
        $line .= $value;
       }
       $data .= trim($line)."\n";
      }
      $data = str_replace("\r", "", $data);

      // return message if query returns no data
      if ( $data == "" )
      {
       $data = "\n(0) Records Found!\n";
      }

      // setup headers with no caching
      header("Content-type: application/octet-stream");
      header("Content-Disposition: attachment; filename=data.xls");
      header("Pragma: no-cache");
      header("Expires: 0");
      print "$header\n$data";
     } else {
     ?> 
     <style>
     body,td,table {font-family:Arial; font-size:10px;} 
     select {font-family:Arial; font-size:12px;}
     </style>
     <table align="center">
     <tr><td align=center><a href="index.php"><font size=2>Back to          Menu</font></a></td></tr>
     <tr><td>
     <form action="extract2.php" method="post">
     Start:
     <select name='smon' size='1'>
     <option value="None">Month</option>
     <option value='January'>January</option>
     <option value='February'>February</option>
     <option value='March'>March</option>
     <option value='April'>April</option>
     <option value='May'>May</option>
     <option value='June'>June</option>
     <option value='July'>July</option>
     <option value='August'>August</option>
     <option value='September'>September</option>
     <option value='October'>October</option>
     <option value='November'>November</option>
     <option value='December'>December</option>
     </select>&nbsp;

     <select name="sday">
     <option value="None">Day</option>
     <?
     for($ctr=1; $ctr<=31;++$ctr){
       if($row[sday] == $ctr){
         print("<option value='$ctr' selected>$ctr</option>");
       }
       else{
         print("<option value='$ctr'>$ctr</option>");
       }
     }
     echo "</select>&nbsp";

     echo "<select name='syear' size='1'>";
       $today = getdate(); 
       $yr = $today['year']; 
     ?>
     <option value="None">Year</option>";
     <option value='2005'>2005</option>";
     <option value='2006'>2006</option>";
     <option value='2007'>2007</option>";
     <option value='2008'>2008</option>";
     <option value='2009'>2009</option>";
     <option value='2010'>2010</option>";
     </select>&nbsp;-&nbsp;
     End:
     <select name='emon' size='1'>
     <option value="None">Month</option>
     <option value='January'>January</option>
     <option value='February'>February</option>
     <option value='March'>March</option>
     <option value='April'>April</option>
     <option value='May'>May</option>
     <option value='June'>June</option>
     <option value='July'>July</option>
     <option value='August'>August</option>
     <option value='September'>September</option>
     <option value='October'>October</option>
     <option value='November'>November</option>
     <option value='December'>December</option>
     </select>&nbsp;

     <select name="eday">
     <option value="None">Day</option>
     <?
     for($ctr=1; $ctr<=31;++$ctr){
       if($row[eday] == $ctr){
         print("<option value='$ctr' selected>$ctr</option>");
       }
       else{
         print("<option value='$ctr'>$ctr</option>");
       }
     }
     echo "</select>&nbsp";

     echo "<select name='eyear' size='1'>";
       $today = getdate(); 
       $yr = $today['year']; 
     ?>
     <option value="None">Year</option>";
     <option value='2005'>2005</option>";
     <option value='2006'>2006</option>";
     <option value='2007'>2007</option>";
     <option value='2008'>2008</option>";
     <option value='2009'>2009</option>";
     <option value='2010'>2010</option>";
     </select>&nbsp;
     <input type="submit" value="Select">
     <input type="hidden" name="qry" value="ok">  
     </tr>
     <tr><td align=center style="font-famiy:Tahoma; font-size:12px; color:777777;">If          you do not enter a date, all records will be displayed.</td></tr>
     </form>
     </table><p>

     <?
     }
     ?>

Ответы [ 2 ]

7 голосов
/ 18 января 2010

Учитывая дату в определенном формате, обычно вы можете просто выполнить быстрое преобразование, используя date и strtotime следующим образом:

// convert old date string to YYYYmmdd format
$date = date('Ymd', strtotime($old_date_string));
1 голос
/ 18 января 2010

вы можете использовать функцию mysql date_format вроде

DATE_FORMAT(dob,'%Y%m%d') AS 'Date of Birth',

дает 20100118 на сегодня

edit: поскольку dob is varchar, вы должны проверить его в foreach и просто использоватьстроковые функции или ответ cballou будет работать для вас

foreach ( $row as $key => $value )
   {
    if ( ( !isset($value) ) OR ( $value == "" ) )
    {
     $value = "\t";
    } 
    else 
    {
 if($key == 'Date of Birth') {
    $exploded_value = explode("/",$value);
    $value = $value[2].$value[0].$value[1];
    // or according to cballou's answer
    //$value = date('Ymd',strtotime($value));
 }
     $value = str_replace('"', '""', $value);
    $value = '="' . $value . '"' . "\t";
 //        ^
 //        Added an equal sign
    }
    $line .= $value;
   }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...