PHP and MySQL Basics: Saving form input in PHP variables
Posted by Daniel at 8:09 pm
form can add interactivity to your site, it enables you to get information or comments from your visitors. saving a value from a form input to a php variable is very easy. refer to the example below.
Example 1: Processing forms in the same php file
Copy and Paste the code below to your text editor and save it as form.php, then run it on your localhost
<html> <head> <title>Saving Form Input in PHP Variables</title> </head> <body> <form method="post"> Enter message : <input type="text" name="msg"> <input type="submit" value="Print Msg"> <?php // stores the form data into a php variable $msg = $_POST['msg']; //Prints the data retrieve from the form echo "You said: <b>$msg</b>"; ?> </body> </html>
Example 2: Processing Form using external php file
Copy and Save the code below to your text editor and save it as form2.php
<html> <head> <title>Saving Form Input in PHP Variables</title> </head> <body> <form action="msghandler.php" method="post"> Enter message : <input type="text" name="msg"> <input type="submit" value="Print Msg"> </body> </html>
Copy and Save the code below to your text editor and save it as msghandler.php in the same folder where form2.php is located, this is the php script that will process the form2.php above
<?php // stores the form data into a php variable $msg = $_POST['msg']; //Prints the data retrieve from the form echo "You said: <b>$msg</b>"; ?>
You Should Get this output in your browser. .
Before clicking the print button

After Clicking the print button

I searched this page for a solution because i seem to get the following error when trying to save the posted variable as another variable:
Unknown column ‘David’ in ‘field list’
The above error is when using this code:
$inputted_name=$_POST["fieldname"];
Yet if i simply echo the variable like so, it does display the variable:
echo $_POST["fieldname"];
output:
David
So why wont it let me save the imported variable as a variable, yet it lets me echo it? This is being developed for a facebook application. Just wondering if that may be why?
Many thanks!