...

View Full Version : Issue in fwrite/fputs.



Veena
08-21-2011, 10:28 PM
Hi all,

I am new to php and trying to add/change/delete records from notepad. Would you guys pls help me. thanks in advance
=======================================================
My Sample data is in events.txt:

001, 20110720, Baby shower
002, 20110605, Health test
123, 20000000, test record
003, 20110701, Doctor visit
004, 20110905, Picknic

I am calling function find_Record with a parm $newid1. Assume that its value is 123

For now I commented out the fwrite line, it is echoing ($buffer1) the 4 records except
"123, 20000000, test record".

However if I remove the comment from fwrite then it is echoing $buffer1 as
001, 20110720, Baby shower
27
0003, 20110701, Doctor visit
28

and now the data in events.txt is:
001, 20110720, Baby shower
001, 20110720, Baby shower
123, 20000000, test record
003, 20110701, Doctor visit
003, 20110701, Doctor visit
=======================================================




function find_Record($newid1) {

$handle1 = @fopen("C:\events.txt", "r+") or die("Oops, could not open file");

while (!feof($handle1)) {

$buffer1 = stream_get_line($handle1, 4096, "\n");
$id1 = substr(htmlentities($buffer1), 0, 3);


if($id1 != $newid1){

echo $buffer1;
echo nl2br("\n");
// echo fwrite($handle1, $buffer1);

}
}

fclose($handle1);
return true;
}


=======================================================
I want to delete the record starts with 123 and rewrite event.txt with remaining 4 records.
I tried with fputs too. I tried using dot operator & "\r\n" for next line in fwrite/fputs. I am not sure what I am doing wrong.
=======================================================

gvre
08-22-2011, 04:06 PM
If the size of events.txt is small, you can use the following

function DeleteRecord($searchId, $filename)
{
$rowsDeleted = 0;
$rows = @file($filename);
if (is_array($rows))
{
$idx = 0;
foreach($rows as $row)
{
list($id) = explode(",", $row);
if ($id == $searchId)
{
unset($rows[$idx]);
$rowsDeleted++;
}
$idx++;
}

if ($rowsDeleted)
file_put_contents("events.txt", implode("", $rows));
return $rowsDeleted;
}
return false;
}

$filename = "c:/events.txt";
$searchId = 123;
$rowsDeleted = DeleteRecord($searchId, $filename);
if ($rowsDeleted === false)
{
// handle error here

}
else
{
// check $rowsDeleted here
}



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum