I'm just starting to scratch the surface with PHP. Sorry to ask a beginner's question but I have spent way too much time research and experimenting and I can't figure it out. Any help would be very much appreciated. I want to be able to delete elements from a text file. The problem is that instead of tagging an element to remove, it wipes out the entire text file. Any help would be much appreciated

Data is something like this:
1|Gray
2|Red
3|Yellow

Code is:

<?php
/*===================================================================================
delete.php allows the users to change and delete data from

the main text file "field_locations.txt" Additional scripts: add.php, edit.php

*/
$filename = "field_locations.txt";
$file_array = file($filename);

echo '<table>';

foreach ($file_array as $key => $value) {
list($col_a, $col_b) = explode("|",trim($value));

echo '
	<tr> 
		<td>' . $col_a . '</td>
		<td>' . $col_b . '</td>
		<td><input type = "checkbox" name="delete[' . $key . ' ]"></td>  
	</tr>';

}

echo '</table>';

// loop through selected items to delete

foreach ($_POST['delete'] as $key =>$value) {
//double check to be sure it was selected
if ($value == "on") {
foreach ($file_array as $file_line) {
list($col_a, $col_b) = explode("|",trim($file_line));
if($col_a !=$value) {
$new_file[]=$col_a . "|" . $col_b;
}
}
}
}

$open_file=fopen($filename,'w');
fwrite($open_file, implode("\n".$file_array));
fclose($open_file);

echo "Deleted an existing record<br/>";

?>

    a database would make this a thousand times easier, faster, cleaner.

      Hi Dagon. Maybe I am approaching it all wrong, but I thought I'd get my hands wrapped around PHP before tackling SQL.

        may as well dive in to sql now, if you plan to do much with php you will be using some db very early on.

          a problem would come when not just one user will add/delete/update new entries into your file.

          in your code the form is missing 🙂

          Where you've set

          $value == "on"

          There is no value="on" in your checkbox

            i've just played with this problem, and you can think of this solution

            (as a matter a fact, it looks like shorter when you make it with database).

            <?php
            /*===================================================================================
            delete.php allows the users to change and delete data from
            the main text file "field_locations.txt" Additional scripts: add.php, edit.php
            =====================================================================================
            */
            
            $filename = "field_locations.txt";
            $file_array = file($filename);
            $open_file=fopen($filename,'w');
            
            
            function add_put($value)
            {
            	global $open_file;
            
            	$row=explode("|",$value);
            	if(empty($row[1]))
            	return;
            
            	if(empty($_POST["delete"][$row[0]])  )
            	{
            	fwrite($open_file, trim($value)."\n");
            				echo '
            				<tr>
            				<td>' . $row[0] . '</td><td>' . $row[1] . '</td>
            				<td><input type = "checkbox" name="delete[' . trim($row[0]) . ']"></td>
            				</tr>';
            	}
            	else
            	{
            		print "<pre>";
            		print "DELETED: ";	
            		print_r( $value);
            		print "</pre>";
            	}
            }
            
            
            echo '<table><form method="post">';
            
            array_map("add_put",$file_array);
            
            echo '</table>
            <input type="submit" name="submit" value="delete">
            </form>';
            
            fclose($open_file);
            
            ?>

              Note that if you do attempt a solution such as djjjozsi suggests above, you should look into file locking.

              If you're deleting a row, you should add a read/write lock to the file until you've finished reading the data, modifying it, and writing it back to the file. There is the possibility that a race condition might occur, and thus you should also consider adding some error-trapping code to check if the file gets locked and handle the condition accordingly.

              Of course, with a database, it's a lot less code/hassle. 😉

                Write a Reply...