Delete a Specific Line?

Discussion in 'PHP' started by dp-user-1, May 5, 2007.

  1. #1
    I have a flat file database, and I'm wondering if I could enter a line, say, on a regular form, and have a PHP script find and delete that line in the flat file?

    Anyone know if this is possible?

    Thanks,
    Peter
     
    dp-user-1, May 5, 2007 IP
  2. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #2
    
    function delete_line($line, $file)
    {
    	if (!$lines = @file($file))
    	{
    		trigger_error("File <i>{$file}</i> does not exists or can't be opened");	
    		return false;
    	}
    
    	unset($lines[$line]);
    	
    	$fp = fopen($file, 'w');
    	fwrite($fp, implode("\n", array_map('trim', $lines)));
    	fclose($fp);
    	
    	return true;
    }
    
    PHP:
    Usage:
    
    if (delete_line(5, 'test.txt'))
    {
    	echo 'Line deleted';
    }
    else
    {
    	echo 'Line not deleted';
    }
    
    ?>
    
    PHP:

    Note that the first line starts with 0, and not 1.
     
    nico_swd, May 5, 2007 IP
  3. dp-user-1

    dp-user-1 Well-Known Member

    Messages:
    794
    Likes Received:
    20
    Best Answers:
    0
    Trophy Points:
    110
    #3
    Wow, thanks a lot!

    I take it you don't mind if I use that code verbatim? (Just in case.)
     
    dp-user-1, May 5, 2007 IP
  4. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #4
    It's all yours. You can keep, sell, or eat it. :)
     
    nico_swd, May 5, 2007 IP
  5. dp-user-1

    dp-user-1 Well-Known Member

    Messages:
    794
    Likes Received:
    20
    Best Answers:
    0
    Trophy Points:
    110
    #5
    I've set it up with a form, and added some simple validation.

    Also added redirects for successful or unsuccessful attempts.

    Thanks again!
     
    dp-user-1, May 5, 2007 IP