fileRead.php
Source of fileRead.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>fileRead.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 read from the file, so use "r".
$theMode = "r";
//prepare the employees array to hold the contents of the file
$employees = array();
//prepare the sql string for insert
$sql = "INSERT INTO employees VALUES";
/*
* If we successfully connect to the file, do all of the file operations.
* Otherwise, print an error.
*/
if($fileConnection = fopen($theFile, $theMode)){
print "<p>Opened file successfully</p>";
while(!feof($fileConnection)){
$line = fgets($fileConnection);
$employees[] = split(",", $line);
}
//close the file
if(fclose($fileConnection)){
print "<p>Closed the file connection successfully.</p>";
}else{
print "<p>Unable to close the file connection.</p>";
}
//connect to the database
$conn = mysql_connect("localhost", "xfd", "xfd123") or die(mysql_error());
mysql_select_db("file_manipulation", $conn) or die(mysql_error());
/*
* prepare sql for insertion of data into employees table, and generate a table
* showing the contents of the file
*/
print "<table>";
for($i = 0; $i < (count($employees)-1); $i++){
$sql .= "(";
$sql .= $employees[$i][0] . ", ";
$sql .= $employees[$i][1] . ", ";
$sql .= $employees[$i][2] . ", ";
$sql .= $employees[$i][3] . ", ";
$sql .= $employees[$i][4] . ", ";
$sql .= $employees[$i][5];
$sql .= ")";
if(($i + 1) < (count($employees)-1)){
$sql .= ", ";
}
print "<tr>\n";
foreach($employees[$i] as $index=>$val){
print "\t<td>$val</td>\n";
}
print "</tr>\n\n";
}
print "</table>";
//insert data into database
$result = mysql_query($sql, $conn);
}else{
print "<p>Unable to connect to the file.</p>";
}
?>
</body>
</html>