|
Posted by Andrew Taylor on 02/18/06 10:41
On 2006-02-18 00:00:15 +0000, Dalibor <dalibor_gv@lycos.com> said:
> I wrote some code for displaying news on my website.
> Code goes like this:
> <?
> $newsfile = 'news.txt';
> echo "<B>TRENUTNE VIJESTI</B><br>\n";
> $data = file($newsfile);
> $data = array_reverse($data);
> echo "<span style=\"normal 11 Verdana; color:#fff; text-align:justify;\">";
> foreach($data as $element) {
> $element = trim($element);
> $pieces = explode("|", $element);
> echo $pieces[2] . "<BR>" . "<span style=\"font:normal 11px
> Tahoma\"><u>Published</u>: " . $pieces[1] . " " . $pieces[0] .
> "</span></span><BR><br>";
> }
> ?>
> I have form that puts content in flat file.
>
> Messages are writen in flat file in format like this:
> 21.Feb 2006.|Dalibor|Some message text
> 14.Feb 2006.|Dalibor|Other message text...
>
> I need piece of code for displaying last 5 messages and for deleting
> certain messages.
> Can you help me? Thanks!
You've done the difficult part, you've got it showing all the news,
and, the way you've done it means it's easy to modify to make it
deletable. I'll give you some pointers in the right direction, then
it's off to php.net/ for you :)
The last 5 messages is easy, in your code you have
foreach($data AS $element) {
}
consider either using a for($i = 0; $i < 5; $i++) loop, or, in
consideration of what comes next;
$count = 0;
foreach($data AS $element) {
if($count < 5) {
// your code in here
}
$count++;
}
You're already getting each line in to an array, and that's an easy way
to work with your data, you're using array_reverse so the first thing
we need to do is preserve the keys
$data = array_reverse($data, true);
Then we need to make a note of which records are which, you're using a
foreach loop, so lets add the keys to the equation:
foreach($data AS $key => $element);
So now you have an extra variable, $key, which is the identifier of
which line in the file you want to delete.
Link your this information back to the original file, or, to another
delete_news.php file, you can do this however you prefer, something
simple like '<a href="delete_news.php?delete='.$key.'">Delete this
News</a>'; would be a start.
Then, all you need to do is open up your news.txt file again,
unset($data[$key]), then write the whole array back to the text file.
As I said you've done most of the work, wrap my suggestions up in to
your code, as with anything, make sure you're sanatising your input
(http://phpsec.org/ is an essential read) and you should be good to go.
Hope this helps
Andrew
Navigation:
[Reply to this message]
|