loveforfire33
loveforfire33

Reputation: 1110

Deleting Line from text file php

i am trying to list all of the lines in a text file and have a delete button next to each one. When the button is pressed that line should be deleted. like below

 Line One Text | Delete
 Line Two Text | Delete
 Line Three Text | Delete

I think i am quite close but cannot get it to work, any ideas why? The lines and buttons display fine, but the delete button does not seem to do anything.

edit.php

<?php
$textFile = file("guestbook.txt");
foreach ($textFile as $key => $val) {
    $line = @$line . $val
        . "<input type='submit' name=$key value='Delete'><br />";
}

$form = "<form name='form' method='post' action='deleter.php'> $line 
    </form>";

echo $form;
?>

deleter.php

if ($delete != "" && $delete > !$lines || $delete === '0') {
    $textFile[$delete] = "";
    $fileUpdate = fopen("data.txt", "wb");
    for ($a = 0; $a < $lines; $a++) {
        fwrite($fileUpdate, $textFile[$a]);
    }
    fclose($fileUpdate);
    header("Location:edit.php");
    exit;
}

foreach ($textFile as $key => $val) {
    $line = @$line . $val . "<a href =?delete=$key> Delete </a><br />";
}
echo $line;
?>

Thanks in advance!

Upvotes: 3

Views: 5296

Answers (2)

Sebastian
Sebastian

Reputation: 5865

One approach could be to query the server with the string to be removed if no line can be equal to another one, e.g., delete.php?str=<your string> and do the deletion of that string (note that I said 'string' not line).

If it's possible for lines to be equal, you should identify the lines and follow a similar approach: delete.php?line=<number>.

This should be easy and you could write a flexible code that deletes lines from a giving file by also passing the filename.

Edit: Example provided following the advise of using a hidden field.

<?php
$html = "<form id='form' method='post' action='delete.php'>";
foreach(array("line 1", "line 2", "line 3") as $key => $value ) {
    $html .= "<span>${value}</span>";
    $html .= "<input type='hidden' name='lineNumber' value='${key}'>";
    $html .= "<input type='submit' value='Delete' name='line'><br>";
}
$html .= "</form>";
echo $html;
?>

In your delete.php get the content of $_POST['lineNumber'] to retrieve the line number.

Upvotes: 1

andrewb
andrewb

Reputation: 3095

What you could do is have some JavaScript which loops through each input and appends each value to a hidden form field. When the form is submitted simply get the value of that form field and overwrite the file with that value.

Upvotes: 0

Related Questions