PDA

View Full Version : fwrite



Wojtek
October 29th, 2003, 17:11
if($_POST['do']=='addnew') {
$title=$_POST['title'];
$news=$_POST['news'];
$fp=fopen(NEWS_FILE,"a");
$formatted=str_replace("\r\n","<br>",$news);
$formatted=str_replace("\n","<br>",$formatted);
$newsto=date("d M Y")."%~#".$title."%~#".$formatted;
fwrite($fp,StripSlashes($newsto)."\n");
fclose($fp);
echo '<center>-- news added --</center>';
}
?>


This ads the content to the end of the file.
What if I want it to be added at the begining?

I've been thinking that putting the content of the whole file in a va, clearing the file, writing the thing to write, and then write the var content, so the actual content to ad is at the begining.

However, wont this be problematic if the file is 50, 100, 400kb in size? can a var hold that much?

Help please :)

keith
October 29th, 2003, 18:20
http://www.php.net/manual/en/function.fopen.php
there's a list there for opening files and how to set the file pointer to where you want.

GregT
October 29th, 2003, 19:37
Im pretty sure if you open it with w it will be at the beginning of the file. If you need to reset to beginning after read/write, use rewind();

Wojtek
October 29th, 2003, 20:00
Ok,

I took a look at that site an "r+" corresponds to what I need. (Open for reading and writing; place the file pointer at the beginning of the file.)

However, now Im having a problem with the news file.


Write news PHP


$fp=fopen(NEWS_FILE,"r+");
$formatted=str_replace("\r\n","<br>",$news);
$formatted=str_replace("\n","<br>",$formatted);
$newsto=date("d M Y")."%~#".$title."%~#".$formatted;
fwrite($fp,StripSlashes($newsto)."\n");



Read news PHP


$startpage=$_GET['page'];
$xnews=file(NEWS_FILE);
$xnews=array_reverse($xnews);
$startpage-=1;
$ubound=count($xnews);

// Next / Prev Buttons

if($startpage<0 || $startpage>=$ubound/PERPAGE) $startpage=0;

if (PERPAGE<$ubound)
if($startpage==0) echo "";
else echo "Previous Link";

if($ubound>PERPAGE)
for($j=1;$j<=ceil($ubound/PERPAGE);$j++) {
if($j==$startpage+1)
echo "";
else
echo "";
}

if(PERPAGE<$ubound)
if($startpage+1>=$ubound/PERPAGE) echo "";
else echo "Next Link";


//below we format the news we need and print it to webpage

for($i=$startpage*PERPAGE;$i<$startpage*PERPAGE+PERPAGE && $i<$ubound;$i++)
{
$crtsplit="";
$crtsplit=explode("%~#",$xnews[$i]);

echo "<br><br><table border=\"0\" cellpadding=\"1\" cellspacing=\"0\" bgcolor=\"#000000\" width=\"100%\"><tr><td>";
echo "<table border=\"0\" cellpadding=\"3\" cellspacing=\"0\" bgcolor=\"#FF9DD0\" width=\"100%\"><tr><td align=left>";
echo "<font color=\"#ffffff\"><center><b>$crtsplit[1]</b></center></font>";
echo "</td></tr></table></td></tr></table><br><br>$crtsplit[2]<br><br>";

}


the news file format is supposed to be:

DATE%~#TITLE%~#CONTENT
DATE%~#TITLE%~#CONTENT



But whenever I add a news using the add news, it always gets overwritten.

------------------------------------------
29 Oct 2003%~#test1%~#test1

------------------------------------------

becomes

------------------------------------------
29 Oct 2003%~#test2%~#test2

------------------------------------------

instead of

------------------------------------------
29 Oct 2003%~#test2%~#test2
29 Oct 2003%~#test1%~#test1
------------------------------------------

spec
October 30th, 2003, 14:03
just store the new info in a var
read the file
append the file info to the new info
re write the file.

BOOM shaka laka.

Wojtek
October 30th, 2003, 15:31
And the code for that would be?

:)

CareBear
October 30th, 2003, 16:55
Moving the file pointer around won't accomplish what you're trying to do as you found out; there isn't a way to "append" data besides at the end of a file without doing it in memory.
I think spec meant something like:


$newsto=date("d M Y")."%~#".$title."%~#".$formatted."\n".file_get_contents("newsfile.txt");
file_put_contents("newsfile.txt", $newsto);

(what's in bold is what I added)

My personal opinion is that this won't scale at all though. As the file containing the news item grows, it will take longer and longer to both write and read the news items.
I'm aware that this might never get to a point where it becomes a problem but on shared hosting and a busy site where many people might be browsing through the news little things quickly add up.

Wojtek
October 30th, 2003, 21:38
What would you recomment then?
Mysql?
I went with flat-file because I dont know how to handle sql databases.

GregT
October 30th, 2003, 22:17
You could possibly append to the end of the file and just reverse it before printing.

bloodyveins
October 30th, 2003, 22:56
agree with corn. the file should be read reversely.

i presume, there is a memory-allocating problem that makes new file-content adding mechanism in front of file pointer unable to reserve the old contents.

keith
October 31st, 2003, 15:06
Originally posted by Wojtek
What would you recomment then?
Mysql?
I went with flat-file because I dont know how to handle sql databases. yes, go with mysql before you learn too much about flat-file and realize how useless it is.

Wojtek
October 31st, 2003, 15:12
Thanks carebear for the code,
its working fine, except 'file_put_contents' gave me an error so i replaced with the 3 open/write/close.

Working perfectly now :)


Keith, got any websites where I could learn the basics of sql?

keith
October 31st, 2003, 15:45
i should probably rephrase that... it's not useless, just extremely clunky when your database gains any kind of popularity or size.

you could check out php.net (http://www.php.net) and mysql.com (http://www.mysql.com)

CareBear
October 31st, 2003, 16:07
My suggestion would be to get comfortable with the general SQL syntax first before anything else. http://sqlcourse.com/ has two fairly good courses building up from basic to more advanced.
http://www.databasejournal.com (which is the same site actually) has a bunch of articles you might want to browse through as well.
http://www.databasejournal.com/features/mysql/archives.php/200201 is a step by step mixed PHP/SQL/MySQL tutorial. The first part only deals with installing everything on your own computer so unless that's something you want to do I'd suggest to skip ahead and start with part two.

spec
November 1st, 2003, 22:00
Why reinvent the wheel? fusion news or coranto?
those are decent flat file.

Wojtek
November 2nd, 2003, 20:14
fusion news or coranto
neither?

look at my 2nd post, thats all the php code.
It's a Very basic code, but does the job ok :)

keith
November 2nd, 2003, 20:38
instead of trying to write to the beginning of the file, why not just explode it into an array and use rsort() to reverse the order?

CareBear
November 3rd, 2003, 04:07
Originally posted by keith
instead of trying to write to the beginning of the file, why not just explode it into an array and use rsort() to reverse the order? Adding a new entry will always take about the same amount of time if you add to the end but reading and parsing the whole thing back and then reverse sorting it will take longer with each new insert.
Since it's for site news you have reads >>> inserts so reads should be cheap which isn't the case here.
If he has MySQL on his hosting account he might as well use it once he gets over the learning curve :-).

keith
November 3rd, 2003, 15:37
ok carebear...

he obviously wants to show the items in reverse chronological order.

he will write to the end of the file, so the items are stored in chronological order.

if he stores the date as a timestamp (and who wouldn't?), he can use rsort() when he retrieves the info from the file.

this will work because it will reverse sort the data numerically since the date is the first piece of info on each line.

then, using foreach(), he can print out the items however he likes.

yeah, it's a bit inconvenient, but not too much considering he is using flatfile. you have to understand flat-file is not the most efficient or user-friendly way of storing data. got it?

i do agree with you though that he should just drop this and learn mysql. it's not that hard once you get into it.

CareBear
November 3rd, 2003, 21:32
I think you missed my point :-)

For the sake of arguement let's say reading one line take 1ms. One line won't take any time at all, but as the number of rows increases so will the time it takes to read the entire file.
Besides that, your script will consume more and more memory as the file grows and you'll suffer an ever increasing overhead from having to sort an array with a larger number of elements (and depending on the algorithm used sorting something that is in the reverse order you want it to be in is the least performant already).

If you want to poke at random values in a flat file you'd get rid of most of the downsides by using a balanced binary tree but the learning curve for that is just a bit steeper then learning MySQL, assuming PHP would even let you build one in a decent manner :-)

Then again most people end up doing "SELECT *"'s so I guess in the end it doesn't make that much difference after all :confused2

Wojtek
November 3rd, 2003, 22:17
Originally posted by CareBear
as the file grows
what size are you talking about?
6kb? 50kb? 500? 1Mb?
Front what size will it have some slowdowns?

CareBear
November 4th, 2003, 00:01
Originally posted by Wojtek
what size are you talking about?
6kb? 50kb? 500? 1Mb?
Front what size will it have some slowdowns? That's not something anyone can answer since it depends a lot on the server.

I timed how long it took for a 7.5Kb file to read and reverse_sort, then a 75Kb file (which took twice as long), then a 750Kb (which took 40 times longer which I don't quite get).

My last post was more about "best practice" then anything. Even if you're going to be using a 1Mb flat file it doesn't mean your visitors will stare at a blank screen for 5 minutes, it's just not a good way to do it.

Learning how MySQL works really isn't that hard at all, it just takes some time and effort and it's just more efficient. Ultimatly it's up to you if you want to get into it or not.

spec
November 4th, 2003, 00:09
Carebear is right. Its much more efficient for you to take the load then your visitors. You are one user, as apposed to thousands of users. And Wojtek My question still stands, why reinvent the wheel. your code allows you to add news, but what about editing, deleting, multi-users? Long term, downloading a script is far wiser, unless there are no scripts that do what you want them to do.

Wojtek
November 4th, 2003, 23:52
Originally posted by spec
Carebear is right. Its much more efficient for you to take the load then your visitors. You are one user, as apposed to thousands of users. And Wojtek My question still stands, why reinvent the wheel. your code allows you to add news, but what about editing, deleting, multi-users? Long term, downloading a script is far wiser, unless there are no scripts that do what you want them to do.
Im not using this script as a news script. But as a poem archive.
http://www.allpoem.com/poems/love/index.php = exemple

let le explain how im using it.

Each poem category has a folder. Ex: love, friendship, famous, etc
in each folder, i have 5 files:
addpoem.php <- script used to add poems
config.php <- config files
index.php <- includes ../../header.php | includes readpoems.php | includes ../../footer.php
poems.dat <- poems stored here
readpoems.php <- script that reads poems from poems.dat and prints them


"Its much more efficient for you to take the load then your visitors. You are one user, as apposed to thousands of users"
I understand what you mean, but i dont know where the problem is? is it in the script that ads the content? or reads the content?

spec
November 5th, 2003, 00:28
Ok let me step back for a sec. My apologies, I dont know how but I missed the fact that you were the one asking for help. I thought you were giving advice..

Ok So lets recap. There have been two methods sugested. One where the data is is ordered when you run the addpoem script. the Next option is to order it when the data is requested.

Now I recommend you order the data when you add the poem. The downside to this is that the larger the file, the longer it will take.

If you did it the other way, although, you would still have the same issue; only the user would suffer the wait. Ontop of that if you have many users running the script at once it would add to the load to the server.

Using Mysql is another option. This is alot easier to do, because alot of the functions required to add, edit and delete data is already there. infact if you were the only one adding poems you could use phpmyadmin to do it and you wouldnt have to bother with any script but the [retrieving] end.

If your host has Mysql installed and/or phpMyAdmin this task would be much easier.

CareBear
November 5th, 2003, 04:26
Originally posted by Wojtek
"Its much more efficient for you to take the load then your visitors. You are one user, as apposed to thousands of users"
I understand what you mean, but i dont know where the problem is? is it in the script that ads the content? or reads the content? Just take a step and think of it as something that would happen in real life :).
You have a notepad file that you keep and add poems to. When you get a new poem you just open it and skip to the end and add the new poem. Same as with your file the oldest poem will be the first one and the most recent poem is that last one.
Since you're using notepad you don't have the concept of page numbers that you'd have in for instance Word.

So if someone asks you to see the most recent poem you hit print, take the stack of printed pages and then reshuffle them so the last page to come out of the printer is at the top, so showing the last poems at the top.
This isn't a particular good way to do it that is it? It's messy and slow since you have to print all of the page just to know where the last poem (or last 10 poems) will be.

Now you could do the same but instead of notepad you use Word. You put each poem on a seperate page so that if you have 50 pages you know you have 50 poems. To print the most recent poem you know you can just print out page 50.
Now since it's word you also have more options when printing so if you wanted to give someone the last 10 poems you'd print pages 41-50 and check the option to reverse the print order so the last poem is the first one to come out, saving you from having to shuffle them manually.
Now this way would save you a lot of time compared to how you'd do it in notepad right?

Compare the notepad example to the way you're doing it now with a .txt file and the Word example to how it would work with MySQL.
Did that help you understand what the problem is?

In the notepad example the bigger that file gets, the longer you'll be waiting for it all to be finished printing (which translates to loading the file into memory), where with Word you'd just put in which specific pages you want to print and it would always take the same amount of time.

CareBear
November 5th, 2003, 04:35
Other advantages of using a database are that you could keep all of the poems in one place and just indicate which category they belong to.
If you keep track of who submitted the poem it's just as easy to ask the database: "show me all the poems that CareBear submitted" as it is to tell it: "give me the last 10 submitted poems" or "give me the last 10 submitted poems in the friendship category".

Wojtek
November 9th, 2003, 15:18
Ok, I've desided to go with mysql :)

I've already created the table format:

| Category | Title | Poem | Author | Score |




<?include "header.php"?>

<?

$dbh=mysql_connect ("localhost", "wojtek_poems", "PASSWORD") or die ('I cannot connect to the database because: ' . mysql_error());

mysql_select_db ("wojtek_poems");

select Category, Title, Poem, Author, Score from wojtek_poems
where Category = 'Love Poems';

?>

<?include "footer.php"?>


By myself, thats all I can do right now :(

However, I look up for some next/previous links script so it only displays 1 poem at a time and next/prev links and I got that:



<?include "header.php"?>

<?

$dbh=mysql_connect ("localhost", "wojtek_poems", "PASSWORD") or die ('I cannot connect to the database because: ' . mysql_error());

mysql_select_db ("wojtek_poems");

if(!isset($poem)) $poem = 0;

$query = "SELECT * FROM wojtek_poems where Category = 'Love Poems' LIMIT " . $poem . ", 1";
$result = mysql_query($query) or die ('I cannot connect to the database because: ' . mysql_error());

$query = "SELECT count(*) as count FROM table";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
$numrows = $row['count'];
if($poem > 0)
echo "<a href=\"" . $PHP_SELF . "?poem=" . ($poem - 1) .
"\">Previous</a><BR>\n";
if($numrows > ($poem + 1))
echo "<a href=\"" . $PHP_SELF . "?poem=" . ($poem + 1) .
"\">Next</a><BR>\n";

?>

<?include "footer.php"?></p>


Does that code make sense? What should I replace/change?
How do I format the results?
Also, I'd like to have a score for each poems. each poem would start with 0 and users can add from +1 to +5 from the page the poem is displayed. And I'll add that number to the existing score filed in the database, this way I could do show top 10 rated poems.

Thanks :)

spec
November 9th, 2003, 17:42
// from first snippet
$query = "select Category, Title, Poem, Author, Score from wojtek_poems where Category = 'Love Poems'";
$result = mysql_query($query);


The second set I bet you downloaded. Its pretty ----ty coding. If you link me to the page to see what it looks like (output) I can help you with that. Do you just want Previous, next buttons?


//from second snippet

//this statement is pretty silly
$query = "SELECT * FROM wojtek_poems where Category = 'Love Poems' LIMIT " . $poem . ", 1";


You see double quotes are used when there is a variable or single quotes inside. So why are there double quotes and then you break out of the string for the variable.

Wojtek
November 9th, 2003, 17:53
I didnt upload yet the files as im having troubles creating the tables first :(



create table Poems
(Category varchar,
Title varchar,
Author varchar,
Poem varchar,
Score number,
Comments varchar);

gives


Database wojtek_poems running on localhost
Error

SQL-query :

CREATE TABLE Poems(
Category varchar,
Title varchar,
Author varchar,
Poem varchar,
Score number,
Comments varchar
)

MySQL said:


You have an error in your SQL syntax. Check the manual that corresponds to your MySQL server version for the right syntax to use near '
Title varchar,
Author varchar,
Poem varchar,
Score number,
Com


The 2nd part is a mix of my 1st part and http://codewalkers.com/tutorials/4/5.html

spec
November 9th, 2003, 18:17
Do you just want Previous next buttons?

Wojtek
November 9th, 2003, 22:37
basically thats what I want to achieve:

---------------------------------------------------------------------
Script #1
- Read content from table: | Category | Title | Author | Poem | Score | Comments
- Display one database result at a time (next/prev buttons)

Script #2
- Add poems to the database
---------------------------------------------------------------------

To read the content from the database, I was thinking of passing arguments like poems.php?Category=Love and it would display one by one poems that match Love as Category. So love poem #5 would be poems.php?Category=Love&Poem=5


I tried to create the database using phpmyadmin and sql query, but I got an error:

---------------------------------------------------------------------
Database wojtek_poems running on localhost
Error

SQL-query :

CREATE TABLE Poems(
Category varchar,
Title varchar,
Author varchar,
Poem varchar,
Score number,
Comments varchar
)

MySQL said:


You have an error in your SQL syntax. Check the manual that corresponds to your MySQL server version for the right syntax to use near '
Title varchar,
Author varchar,
Poem varchar,
Score number,
Com
---------------------------------------------------------------------

spec
November 10th, 2003, 00:02
Ok We'll work on this in 3 parts.
First the mysql. Your mysql syntax is wrong. you do not specify the lengths of each column or have an index. I ALWAYS use an auto increment index as it helps with searching. If you can create as many tables as you want I recommend seperating each "category" into seperate tables. That way there is less data to search. But here is the code:



CREATE TABLE `poems` (
`id` INT( 4 ) DEFAULT '0' NOT NULL AUTO_INCREMENT ,
`category` VARCHAR( 50 ) DEFAULT 'None' NOT NULL ,
`title` VARCHAR( 50 ) DEFAULT 'None' NOT NULL ,
`author` VARCHAR( 100 ) DEFAULT 'None' NOT NULL ,
`poem` TEXT NOT NULL ,
`score` INT( 5 ) NOT NULL ,
`comments` VARCHAR( 250 ) NOT NULL ,
UNIQUE (
`id`
)
);

Notice I made an id, when inputing data NEVER fill this field in. It automatically fills itself in. Next I made peom a TEXT field. with varchar you have a maximum of 255 characters (including whitespace) so if you have a large poem it will not fit in a varchar field. and of course at the end I made id unique.

I recommend you seperate each category into tables. so instead of 'poems' you would use many tables like 'love'



CREATE TABLE `love` (
`id` INT( 4 ) DEFAULT '0' NOT NULL AUTO_INCREMENT ,
`category` VARCHAR( 50 ) DEFAULT 'None' NOT NULL ,
`title` VARCHAR( 50 ) DEFAULT 'None' NOT NULL ,
`author` VARCHAR( 100 ) DEFAULT 'None' NOT NULL ,
`poem` TEXT NOT NULL ,
`score` INT( 5 ) NOT NULL ,
`comments` VARCHAR( 250 ) NOT NULL ,
UNIQUE (
`id`
)
);

Wojtek
November 10th, 2003, 00:09
I did what you suggested. 1 table/per category instaed of All in one table

------------------------------------------------------------------------
CREATE TABLE `love` (
`id` INT( 4 ) DEFAULT '0' NOT NULL AUTO_INCREMENT ,
`title` VARCHAR( 50 ) DEFAULT 'None' NOT NULL ,
`author` VARCHAR( 100 ) DEFAULT 'None' NOT NULL ,
`poem` TEXT NOT NULL ,
`score` INT( 5 ) NOT NULL ,
`comments` TEXT NOT NULL ,
UNIQUE (
`id`
)
);
------------------------------------------------------------------------


How do I add content into the fields using a script?

Wojtek
November 10th, 2003, 00:22
I came up with such code:



<?php
if($Title) {
$Title=$_GET['Title'];

$dbh=mysql_connect ("localhost", "wojtek_poems", "PASSWORD") or die ('I cannot connect to the database because: ' . mysql_error());

mysql_select_db ("wojtek_poems");

insert into love
(Author, AuthorEmail, Title, Cateory, Poem, Comment)
values ($_GET['Author'], $_GET['AuthorEmail'], $_GET['Title'], $_GET['Category'], $_GET['Poem'], $_GET['Comment']);

echo "Poem Added";
}
?>



<?include "../header.php"?>

<font face="verdana" size="1">
<form method="get" action="AddPoem.php">
<p align="center"><b>Add a Poem</b></p>
<div align="center">
<center>
<table border="0" cellspacing="0" cellpadding="0">
<tr>
<td>

<font face="verdana" size="1">Author:
</font>

</td>
<td>

<font face="verdana" size="1">
<input type="text" name="Author" size="50">
</font>

</td>
</tr>
<tr>
<td>

<font face="verdana" size="1">Author Email/Url:
</font>

<p>&nbsp;</td>
<td>

<font face="verdana" size="1">
<input type="text" name="AuthorEmail" size="50">
</font>

<p>&nbsp;</td>
</tr>
<tr>
<td>

<font face="verdana" size="1">
Poem Title:
</font>

</td>
<td>

<font face="verdana" size="1">
<input type="text" name="Title" size="50">
</font>

</td>
</tr>
<tr>
<td>

<font face="verdana" size="1">
Category:
</font>

</td>
<td>

<font face="verdana" size="1">
<select size="1" name="Category">
<option>Birthday</option>
<option>Childrens</option>
<option>Christmas</option>
<option>Easter</option>
<option>Famous</option>
<option>FathersDay</option>
<option>Friendship</option>
<option>Graduation</option>
<option>Humorous</option>
<option>Love</option>
<option>Marriage Poems</option>
<option>MothersDay</option>
<option>NewYears</option>
<option>Passover</option>
<option>Philosophical</option>
<option>Sonnets</option>
<option>ThankYou</option>
<option>ValentinesDay</option>
<option>Other</option>
</select>
</font>

</td>
</tr>
<tr>
<td>

<font face="verdana" size="1">
Poem:
</font>

</td>
<td>

<font face="verdana" size="1">
<textarea name="Poem" cols="50" rows="10"></textarea>
</font>

</td>
</tr>
<tr>
<td><font face="verdana" size="1">Comment:</font></td>
<td>

<font face="verdana" size="1">
<input type="text" name="Comment" size="50">
</font>

</td>
</tr>
</center>
<center>
<tr>
<td colspan="2">
<p align="center">&nbsp;

</td>
</tr>
<tr>
<td colspan="2">
<p align="center">

<font face="verdana" size="1">
<input type="submit" value=" Add Poem ">
</font>

</td>
</tr>
</table>
</center>
</div>
</form>
</font>

<?include "../footer.php"?>

Makes sense? Good coding?

spec
November 10th, 2003, 01:03
sorry but no but close.

your mysql query is all wrong. please see below.
If you are allowing users to add poems then you will need alot of error checking, which I dont have added. If it is just you then you should be ok with maybe adding a login, or putting it in a passworded folder.
The first bit checks if action is set. action just checks to see if they submited. next the script checks for empty fields, mind you if you want users to submit poems your going to need to tighten security or you will get ALOT of abuse.
your mysql connection is good, and I added some really basic database adding. If this is going to be public PLEASE add some more security.




<?php
if(!empty($_GET['action'])) {
if($_GET['$action'] != 'add') die('Please use the form to add');
if(!empty($_GET['Title'])) $title= $_GET['Title'];
if(!empty($_GET['Author'])) $author = $_GET['Author'];
if(!empty($_GET['AuthorEmail'])) $email = $_GET['AuthorEmail'];
if(!empty($_GET['Category'])) $cat = $_GET['Category'];
if(!empty($_GET['Poem'])) $poem = $_GET['Poem'];
if(!empty($_GET['Comment'])) $comments = $_GET['Comment'];

$dbh=mysql_connect ('localhost', 'wojtek_poems', 'PASSWORD') or die ('I cannot connect to the database because: ' . mysql_error());

mysql_select_db ('wojtek_poems');

$query = "insert into love
( title, author, poem, comments)
values ('$title', '$author', '$poem', '$comments')";
$result = mysql_query($query);

echo "Poem Added";
}
?>



<?include "../header.php"?>


....

<form method="get" action="AddPoem.php?action=add">

spec
November 10th, 2003, 01:07
update



if(!empty($_GET['Title'])) $title= $_GET['Title'];
else die('Please add a title');
if(!empty($_GET['Author'])) $author = $_GET['Author'];
else die('Please add a author');
if(!empty($_GET['AuthorEmail'])) $email = $_GET['AuthorEmail'];
else die('Please add a Author Email');
if(!empty($_GET['Poem'])) $poem = $_GET['Poem'];
else die('Please add a Poem');
if(!empty($_GET['Comment'])) $comments = $_GET['Comment'];
else die('Please add Comments');

and you may notice that AuthorEmail isnt actually used since you never created that column in the table!

and another thought. Dont use Get for your method. Use Post. Imagine a URL with The Raven in it. Quote the Raven, Crap I think my computer just exploded.

Wojtek
November 10th, 2003, 07:56
I'll be the only one adding poems, that file will be in a password protected folder so its ok :)

I used AuthorEmail here because I droped the other table and created a new one with that field.

And what do you mean by using post?
Instead of
<form method="get" action="AddPoem.php?action=add">
use
<form method="post" action="AddPoem.php?action=add">
?

Wojtek
November 10th, 2003, 08:01
Is the syntax ok like that?

------------------------------------------------------------------
$query = "insert into " . $cat . "
(Author, AuthorEmail, Title, Poem, Comment)
values ('$author', '$email', '$title', '$poem', '$comment')";
------------------------------------------------------------------

So it checks what I've selected from the category dropdown and uses that as the table name into where to add.

Wojtek
November 10th, 2003, 08:47
yay!
It's working :)



<?php
if(!empty($_GET['Author'])) {
if(!empty($_GET['Author'])) $author = $_GET['Author'];
if(!empty($_GET['AuthorEmail'])) $email = $_GET['AuthorEmail'];
if(!empty($_GET['Title'])) $title= $_GET['Title'];
if(!empty($_GET['Category'])) $cat = $_GET['Category'];
if(!empty($_GET['Poem'])) $poem = $_GET['Poem'];
if(!empty($_GET['Comment'])) $comment = $_GET['Comment'];

$dbh=mysql_connect ('localhost', 'wojtek_poems', 'password') or die ('I cannot connect to the database because: ' .

mysql_error());

mysql_select_db ('wojtek_poems');

$query = "insert into " . $cat . "
(Author, AuthorEmail, Title, Poem, Comment)
values ('$author', '$email', '$title', '$poem', '$comment')";
$result = mysql_query($query);

echo "Poem Added";
}
?>

<?include "header.php"?>

<form method="get" action="test.php">

<form method="post" action="test.php?action=add"> didnt work.
It always displayed 'Please use the form to add' on a white page.

Oki, script #2 is working! :) now the main part....
Read from the database and print one entry at a time with prev/next buttons...

spec
November 10th, 2003, 11:09
<?
if(!empty($_GET['Category']))
{

$category = $_GET['Category'];

if(!empty($_GET['Poem'])) $poem_id = $_GET['Poem'];
else $poem_id = 1;
$query = "select * from" . $category . "where id='$poem_id' limit 1";
$result = mysql_query($query) or die(mysql_error());
// check to see if this poem actually exists
if(!num = mysql_num_rows($result)) die('Error message when there is no poem with that cat or id');

// if it does
while($row = mysql_fetch_assoc($result))
{

$author = $row['author'];
$email = $row['email'];
$title = $row['title'];
$poem = $row['poem'];
$comment = $row['comment'];

##
##Insert the poem output here
##

}
$next_poem = poem_id + 1;
if($poem_id < 1) $prev_poem = 1;
else $prev_poem = $poem_id - 1;

?>
<a href ="Poem.php?Category=<? echo $category; ?>&Poem=<? echo $prev_poem; ?>">Previous</a>
<a href ="Poem.php?Category=<? echo $category; ?>&Poem=<? echo $next_poem; ?>">Next</a>
<?
}
else
{
##
## Put here what you want to happen if no category is selected.
##

}


Remember I cant test any of this so do some error checking, and do with it what you like.

Wojtek
November 10th, 2003, 17:01
Thanks Alot Spec! :classic2:

Any way I can thank you? :)

spec
November 10th, 2003, 20:22
Big ol Thanks would do. If you want to paypal me a new car or maybe some mail order brides my email is spectral2k###hotmail.com

Wojtek
November 10th, 2003, 23:50
last few questions :)


When I add poems, this one for example:


Happy birthday, darling!
Even though you're not with me.
Right now you're with someone else
Temporarily.

I know I am the wild cat
Who'll get you in the end,
Not only your hot lover, but
Your best and truest friend.

So have a happy birthday
And remember my sweet kiss.
It's waiting for you when you turn
To me, your fated bliss.

It gets displayed like that:


Happy birthday, darling! Even though you're not with me. Right now you're with someone else Temporarily. I know I am the wild cat Who'll get you in the end, Not only your hot lover, but Your best and truest friend. So have a happy birthday And remember my sweet kiss. It's waiting for you when you turn To me, your fated bliss.

I'd need to make the submit script put a <br> at the end of each line. and <br><br> when there is an empty line.



"SELECT * from Love ORDER by id ASC"
How can I search from all the tables?
"SELECT * from * ORDER by id ASC" dosnt work.


Also for the score thingy.
Since each poem has an ID, and Score field, I'd like to be able to update the content of the score field.

something like that is ok?


$id=$_GET['id'];
$num=$_GET['num'];
$current=$_GET['current'];
$score=($current+$num)

$db = mysql_connect("localhost", "wojtek_poems", "password");
mysql_select_db("wojtek_poems", $db) or die(mysql_errno() . ": " . mysql_error() . "<br>");

$sql = 'UPDATE `Love` SET `Score` = \'$score\' WHERE `id` = \'$id\' LIMIT 1 ;
$result = $nav->execute($sql, $db, "mysql");

Sorry I cant paypal you a new car :)

spec
November 11th, 2003, 01:31
for adding <BR> try this:



<?

....

if(!empty($_GET['Category'])) $cat = $_GET['Category'];
if(!empty($_GET['Poem'])) $poem = $_GET['Poem'];
//add this line
$poem = preg_replace( "/\n/", "<br>", $poem);
if(!empty($_GET['Comment'])) $comment = $_GET['Comment'];

...

?>