So from what I understood, this would write the inputs to a file with the
name action page. But i have played around and nothing seems to be happening.
No, that is not what <form action="action_page.php">
would do.
When the user clicks the submit button, that would SEND the user over to a different web page, as specified in the action=
attribute of the <form>
tag - in this case, one called action_page.php
. If action_page.php
just said:
<h1>Hello</h1>
(and that was the full content of the page), then Hello would appear on the screen and nothing at all would be done with the form data.
So, you need to create a page that gets the data variables sent over from the first page and does something with them. The variables are formed on the first page like this:
<input name="first_name" type="text" />
When the form is submitted, there will be a variable called first_name
with the contents being whatever the user typed.
On the second page (action_page.php
), you need to get those variables:
$fname = $_REQUEST['first_name'];
Now, you have what the user typed for a first name in a variable called $fname
(all PHP variables must begin with a $).
So if this was the full contents of action_page.php
, submitting the form would output "Hello John, how are you?":
<?php
$fname = $_REQUEST['first_name'];
?>
<h1>Hello <?php echo $fname; ?>, how are you?</h1>
Try it.
Also read this important article:
https://stackoverflow.com/a/54757176/1447509
Update - response to comment:
It is the user who types into the form fields, so nothing in there would tell the PHP processing file (action_page.php
in your example) where to put the data. That is your (the developer's) decision. As Rick said in his comment, you have options. 99% of the time we stick the info into a MySQL
(now called MariaDB
) database - but you could practice by first saving data into a text file.
Using the above example, you can change the action_page.php
file to this:
<?php
$fname = $_REQUEST['first_name'];
?>
$myFile = fopen('___mytest.txt', 'w');
$fwrite($myFile, "Received from the HTML side: " . $fname);
fclose($myFile);
Note: Be verrrry careful to end every line with a semi-colon ;
-- EVERY LINE! When PHP breaks, there is no message - it just stops. The most common mistake is forgetting to end a line with the semi-colon. (I started the file name with 3 underscore chars just to make it stand out and appear at the top of the other files.)
When you get that working, then your next step is to create a MySQL database and figure out how to write the data into that. There are somewhere close to a gazillion YouTube tutorials that will help.
Writing the data to a text file (as a first step) will: (1) prove to you that you're on the right track, (2) prove that everything works so far, and (3) give you successful experience receiving data from HTML and saving it somewhere.
PHP - Secure member-only pages with a login system
https://www.thoughtco.com/write-to-a-file-from-php-2693790