Jump to content

[SOLVED] Delete From Flat file database ?


chocopi

Recommended Posts

I have recently started to code a Flat file database (just for fun) and it's going fine, but I was wondering whats the best way to delete a line from the file. I have this code below and I would like to add a delete button besides each line, which would obviously delete that line. But I do not know the best way to go around doing this as I don't know any specific functions to use.

 

<?php
$filename = "db.txt";
$lines = file($filename);
foreach($lines as $line)
{
list($id,$username,$password) = explode(",", $line);
if($id != 0)
{
	$username = ucwords($username);
	echo "{$id} {$username} {$password}<br />";
}
}
?>

 

So is there a simple function I can use I will I have to use multiple ones :(

 

And help/advice/guidance would be greatly appreciated,

 

Many thanks,

 

~ Chocopi

Link to comment
Share on other sites

Thanks hitman6003 for the linky, it seems like it could be very helpful.

 

@Barand: How would I go about re-writing the file or do you mean i should just use explode to single out the line and just piece it back together and write over the whole file?

 

Many Thanks,

 

~ Chocopi

Link to comment
Share on other sites

That's right

 

<?php
$id_to_delete = 20;         // assuming that's what was selected

$filename = "db.txt";
$lines = file($filename);

$handle = fopen($filename. 'w');
foreach($lines as $line)
{
list($id,$username,$password) = explode(",", $line);
if($id != $id_to_delete)
{
	fwrite ($handle, $line);
}
}
fclose ($handle);
?> 

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.