I am writing a web page that will display the content of a CSV file in a table and I want to add a Delete button at the end of each row that would delete that line in CSV file, but I'm having some problems with the delete button. Here is what i have so far:
<?php
$fileName = "Contacts.csv";
echo "<table> \n\n";
$f = fopen("Contacts.csv", "r");
$i=0;
while (($line = fgetcsv($f)) !== false) {
echo "<tr>";
foreach ($line as $cell) {
echo " <td> " . htmlspecialchars($cell) . " </td> ";
}
echo "<td><button type=\"button\" onclick= ?????? >Delete</button></td>";
echo "</tr>\n";
$i++;
}
fclose($f);
echo "\n</table>";
$string="Hello";
?>
And then there is a function that I found online for deleting the line in CSV that takes two parameters, the name of CSV file and the nuber of the line to delete.
function delLineFromFile($fileName, $lineNum){
// check the file exists
if(!is_writable($fileName))
{
// print an error
print "The file $fileName is not writable";
// exit the function
exit;
}
else
{
// read the file into an array
$arr = file($fileName);
}
// the line to delete is the line number minus 1, because arrays begin at zero
$lineToDelete = $lineNum-1;
// check if the line to delete is greater than the length of the file
if($lineToDelete > sizeof($arr))
{
// print an error
print "You have chosen a line number, <b>[$lineNum]</b>, higher than the length of the file.";
// exit the function
exit;
}
//remove the line
unset($arr["$lineToDelete"]);
// open the file for reading
if (!$fp = fopen($fileName, 'w+'))
{
// print an error
print "Cannot open file ($fileName)";
// exit the function
exit;
}
// if $fp is valid
if($fp)
{
// write the array to the file
foreach($arr as $line) { fwrite($fp,$line); }
// close the file
fclose($fp);
}
echo "Contact was deleted successfully!";
}
So actually the problem is that I don't know how to put the appropriate number of line to delete in the function delLineFromFile. Does anyone know how to do that?