Jump to content

Problem deleting item from file


takethelongroad

Recommended Posts

Hi everyone,

                this is a really great and helpful place, and i hope you guys can give me a hand with a little problem i have with php, I am new to the language.

 

My code reads data from a text file, where each line in the text file is an individual news item, and stores each line into an array element so it can be formatted on screen. Above each item is a delete link, which should allow the user to delete that specific item.

 

The problem arises when the user clicks the delete link, the code merely deletes the first news item no matter which one is clicked. So i think that the code does not assign the key value of the array element to the id attribute in the href. In fact i have a small debug snippet echo "you selected to delete item" . $id; and the value displayed on screen is always 0.

 

Can anyone please help?!?!

 

<?php

	$fp = fopen('news.txt','a');
	if(!$fp)
		{
    		echo "Error opening file!";
		exit;
		}

	$data = file('news.txt');

	foreach($data as $key=>$element)
	{
		$element = trim($element);
		$pieces = explode("|", $element);

		echo "<a href=\"" . $PHP_SELF . "?action=delete&id=" . $key . "\">Delete</a>\n";
		echo stripslashes("<div style=\"padding-left:100px; padding-top:16px; padding-right:10px; width:600px\"><img src=\"fs1.png\"> <br style=\" line-height:7px \"><p>" . $pieces[1] . " posted " . $pieces[0] . "<BR>" . $pieces[2] . "<BR>key for this news is: " . $id . "</p></div>");
	}

$action = $_REQUEST['action'];
		if ($action == 'delete')
	{

		echo "you selected to delete item" . $id;
		$data = file('news.txt');
		array_splice($data,$id,1); 
		$fp = fopen('news.txt','w');
		foreach($data as $element)
		{
			fwrite($fp, $element);
		}
		fclose($fp); 
	}
?>

 

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.