Website forms allow users to submit data to Internet services. Developers build these forms in HTML using various input controls for different types of data. When the user submits a form, the browser will normally send the data to a server side script in a language such as PHP, which is specified as part of the form code. Inside this script, PHP code can capture the passed data and process it. Often, server side scripts in PHP write user data to MySQL databases.
Web forms help sites to capture user data for various purposes, for example signing users up with new accounts. When creating Web forms, developers can choose from a range of user controls, including text-fields, buttons, check-boxes, drop-down lists and radio buttons. HTML form elements can include name attributes so that the data they capture can be identified in PHP scripts. The following sample markup demonstrates how to include a text-field in a Web form:
Enter some text: <input type="text" name="usertext" />
Web forms can indicate a PHP script for the browser to send data to when the user presses the submit button. The following opening form tag demonstrates this:
<form action="process_data.php" method="post">
<!--form input elements-->
This specifies that the data should be sent to the "process_data" PHP script when the user submits it. The following sample markup demonstrates the submit button, which normally appears at the end of the form, before the closing form tag:
<input type="submit" value="Submit" />
When the user presses the button, the browser passes all data captured within the form to the specified server side script in the post variable.
PHP scripts can access data passed to them inside the post variable. The following sample PHP code demonstrates how to store a passed data item from the form in a variable:
$user_text = $_POST["usertext"];
This variable contains whatever the user entered in the text-field. The browser lifts any text in the field when the user presses submit. The PHP script can access any passed data items using the name attribute values of the form elements. The PHP script can then carry out processing on this data, including writing it to a MySQL database.
PHP scripts can use a variety of standard functions for connecting to and querying MySQL databases. The following sample code demonstrates a PHP script building a query string to insert user data into a specific database table:
$insert_query = "INSERT INTO user_info (infoID, infoText) VALUES (null, '".$user_text."')";
This code builds the passed data variable into the query string. The script can then execute the insert query on the database as follows:
When this line executes, the new data record will be added to the table.