|Complete beginner's question (have mercy)|
Can PHP do this?
Coming from a 'traditional' programming environment I have hard time adjusting to PHP; I have started by recoding some simple C programs in PHP. What gets me is statelessness of http. Here is a silly (pseudocode) example:
write "how many grades?
total = 0
for i = 1 to n
write "enter grade"
total = total + grade
write "your average is", total/n
How do you do this in PHP? (without hidden fields, session IDs, arrays ....)
I did "solve" it in a way that I am pretty sure is not right:
On the first page ask for n
On the second page generate form with n entries for values. Pass these via hidden fields (as an array) to the third php page which uses the loop to calculate the average. (OK, you are now laughing)
Please, point me in the right direction ...
|How do you do this in PHP? (without hidden fields, session IDs, arrays ....) |
You don't. :D ;)
If you want to have a stateful-application, you have to deal with sessions (or other means of transporting state, i.e. through GET/POST Parameters, just like you have done), there is no way around that. Other than reformulating your problem/use-case as a stateless problem (if possible):
- Make a textbox and require the user to input one grade per line.
Your approach is actually pretty common and not as bad as you seem to think.
As noted, your struggle won't necessarily be with PHP, but the stateless connection which is both the greatness as well as the boon of HTTP. Coming from a "terminal-interface, always connected" type environment into the stateless world of this protocol is a big jump and takes some thinking before it all clicks, but rest assured, it will click.
I just wanted to add that PHP uses a lot of functions similar to C, and is itself written in C. I think once you nail down the whole "stateless" concept, you are going to love PHP.
both the greatness as well as the boon of HTTP.
I think he meant 'bane'.... :-)
hehe, yeah, I did. My spell-checker didn't catch that...
...no wait, I mean, that's how we say it in Wisconsin...
...no wait, I've got more excuses...
Go pick up the O'Reilly PHP book. Its useful and should get you moving easily.
I gather you're thinking "3 pages to add a few numbers, sheesh."
For something this simple, of course you'll want to do this with one page. You can do this by having PHP check its input & figure out where it is:
"I got a list of numbers? I'll add them?"
"I got how many numbers to add? I'll present a list of that length."
"Did I get nothing? I'll start at the beginning."