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
https://forums.phpfreaks.com/topic/64517-solved-delete-from-flat-file-database/
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

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);
?> 

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.