fileWrite.php

Source of fileWrite.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html lang="EN" dir="ltr" xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="content-type" content="text/xml; charset=utf-8" />
    <title>fileWrite.php</title>

    <style type="text/css">
      td{
        border: 1px solid #000;
        margin: 0px;
        padding: 5px;
      }

      table{
        border-collapse: collapse;
        border-spacing: 0px;
      }
    </style>
  </head>

  <body>
<?
//This is the CSV file we want to create
$theFile = "employees.csv";
//We want to completely over-write the file, so use "w".
$theMode = "w";
//prepare the string to be filled with employees and printed to the file.
$employees = "";

/*
* If we successfully connect to the file, do all of the file operations.
* Otherwise, print an error.
*/
if($fileConnection = fopen($theFile, $theMode)){

  //connect to the database
  $conn = mysql_connect("localhost", "xfd", "xfd123") or die(mysql_error());
  mysql_select_db("file_manipulation", $conn) or die(mysql_error());

  //get the employees out of the employee table
  $sql = "SELECT * FROM employees";
  $result = mysql_query($sql, $conn);

  //for each employees row, print a new table row,
  //and add the employee to the text string to be printed to the file.
  print "<table>";
  while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
    print "<tr>\n";

    foreach($row as $col=>$val){
      print "\t<td>$val</td>\n";

      //escape commas in string
      $val = str_replace(",", "", $val);

      $employees .= $val . ",";
    }
    print "</tr>\n\n";

    //go to the next line in the CSV file to prepare for the next record.
    $employees .= "\n";
  }
  print "</table>";

  //print the employees to the file
  if(fwrite($fileConnection, $employees)){
    print "<p>$employees successfully written to the file.</p>";
  }else{
    print "<p>There was an error while attempting to write $employees to the file.</p>";
  }

  //close the file
  if(fclose($fileConnection)){
    print "<p>Closed the file connection successfully.</p>";
  }else{
    print "<p>Unable to close the file connection.</p>";
  }
}else{
  print "<p>Unable to connect to the file.</p>";
}

?>
  </body>
</html>