Retrieving Submitted Data
Example 11-1 is only one part of the multipart form-handling process. If you enter a name and
click the Submit Query button, absolutely nothing will happen other than the form being
redisplayed. So now it’s time to add some PHP code to process the data submitted by the form.
Example 11-2 expands on the previous program to include data processing. Type it or modify
formtest.php by adding in the new lines, save it as formtest2.php, and try the program for
yourself. The result of running this program and entering a name is shown in Figure 11-2.
Example 11-2. Updated version of formtest.php Your name is: $name
What is your name?
_END; ?> The only changes are a couple of lines at the start that check the $_POST
associative array for the field name having been submitted. Chapter 10 introduced the $_POST
associative array, which contains an element for each field in an HTML form. In Example 11-2,
the input name used was name and the form method was Post, so ele‐ ment name of the
$_POST array contains the value in $_POST['name']. The PHP isset function is used to test
whether $_POST['name'] has been assigned a value. If nothing was posted, the program
assigns the value (Not entered); other‐ wise, it stores the value that was entered. Then a single
line has been added after the statement to display that value, which is stored in $name
PHP $_GET
PHP $_GET is a PHP super global variable which is used to collect form data
after submitting an HTML form with method="get".
$_GET can also collect data sent in the URL.
Assume we have an HTML page that contains a hyperlink with parameters:
<html>
<body>
<a href="test_get.php?subject=PHP&web=W3schools.com">Test $GET</a>
</body>
</html>
When a user clicks on the link "Test $GET", the parameters "subject" and "web"
are sent to "test_get.php", and you can then access their values in
"test_get.php" with $_GET.
The example below shows the code in "test_get.php":
<html>
<body>
<?php
echo "Study " . $_GET['subject'] . " at " . $_GET['web'];
?>
</body>
</html>
PHP $_POST
PHP $_POST is a PHP super global variable which is used to collect form data
after submitting an HTML form with method="post". $_POST is also widely used
to pass variables.
The example below shows a form with an input field and a submit button. When
a user submits the data by clicking on "Submit", the form data is sent to the file
specified in the action attribute of the <form> tag. In this example, we point to
the file itself for processing form data. If you wish to use another PHP file to
process form data, replace that with the filename of your choice. Then, we can
use the super global variable $_POST to collect the value of the input field:
<html>
<body>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
Name: <input type="text" name="fname">
<input type="submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input field
$name = $_POST['fname'];
if (empty($name)) {
echo "Name is empty";
} else {
echo $name;
?>
</body>
</html>
PHP $_REQUEST
PHP $_REQUEST is a PHP super global variable which is used to collect data
after submitting an HTML form.
The example below shows a form with an input field and a submit button. When
a user submits the data by clicking on "Submit", the form data is sent to the file
specified in the action attribute of the <form> tag. In this example, we point to
this file itself for processing form data. If you wish to use another PHP file to
process form data, replace that with the filename of your choice. Then, we can
use the super global variable $_REQUEST to collect the value of the input field:
<html>
<body>
<form method="post" action="<?php echo
$_SERVER['PHP_SELF'];?>">
Name: <input type="text" name="fname">
<input type="submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input field
$name = $_REQUEST['fname'];
if (empty($name)) {
echo "Name is empty";
} else {
echo $name;
}
?>
</body>
</html>
PHP $_SERVER
$_SERVER is a PHP super global variable which holds information about
headers, paths, and script locations.
The example below shows how to use some of the elements in $_SERVER:
<?php
echo $_SERVER['PHP_SELF'];
echo "<br>";
echo $_SERVER['SERVER_NAME'];
echo "<br>";
echo $_SERVER['HTTP_HOST'];
echo "<br>";
echo $_SERVER['HTTP_REFERER'];
echo "<br>";
echo $_SERVER['HTTP_USER_AGENT'];
echo "<br>";
echo $_SERVER['SCRIPT_NAME'];
?>
Connect PHP to MySQL
How we can connect PHP to MySQL?
PHP 5 and later can work with a MySQL database using:
● MySQLi extension (the ‘i’ is abbreviation for improved)
● PDO (PHP Data Objects)
Which one should we use MySQLi or PDO?
Both MySQLi and PDO have their recompenses:
● PDO will work with 12 different database systems, whereas
MySQLi will only work with MySQL databases.
● So, if you have to shift your project to use alternative database,
PDO makes the process easy. You only have to change the
connection string and a few queries. With MySQLi, you will need to
rewrite the complete code — queries included.
● Both are object-oriented, but MySQLi also offers a procedural API.
In short, you can choose whichever you want if you want to stick to MySQL
otherwise you should go with PDO.
Connection to MySQL using MySQLi
It can be done in two ways:
MySQLi Object-Oriented
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Connection
$conn = new mysqli($servername,
$username, $password);
// For checking if connection is
// successful or not
if ($conn->connect_error) {
die("Connection failed: "
. $conn->connect_error);
echo "Connected successfully";
?>
MySQLi Procedural
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Connection
$conn = mysqli_connect($servername,
$username, $password);
// Check if connection is
// Successful or not
if (!$conn) {
die("Connection failed: "
. mysqli_connect_error());
echo "Connected successfully";
?>
Select Data From a MySQL Database
The SELECT statement is used to select data from one or more tables:
SELECT column_name(s) FROM table_name
or we can use the * character to select ALL columns from a table:
SELECT * FROM table_name
Select Data With MySQLi
The following example selects the id, firstname and lastname columns
from the MyGuests table and displays it on the page:
Example (MySQLi Object-oriented)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " "
. $row["lastname"]. "<br>";
}
} else {
echo "0 results";
$conn->close();
?>
Run example »
Code lines to explain from the example above:
First, we set up an SQL query that selects the id, firstname and
lastname columns from the MyGuests table. The next line of code runs
the query and puts the resulting data into a variable called $result.
Then, the function num_rows() checks if there are more than zero rows
returned.
If there are more than zero rows returned, the function fetch_assoc()
puts all the results into an associative array that we can loop through.
The while() loop loops through the result set and outputs the data from
the id, firstname and lastname columns.
PHP | mysqli_close() Function
MySQLi Procedural procedure:
To close the connection in mysql database we use php function
mysqli_close() which disconnect from database. It require a parameter
which is a connection returned by the mysql_connect function.
Syntax:
mysqli_close(conn);
If the parameter is not specified in mysqli_close() function, then the last
opened database is closed. This function returns true if it closes the
connection successfully otherwise it returns false.
Below program illustrate the mysqli_close() function
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Creating connection
$conn = mysqli_connect($servername, $username, $password);
// Checking connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
// Creating a database named newDB
$sql = "CREATE DATABASE newDB";
if (mysqli_query($conn, $sql)) {
echo "Database created successfully with the name newDB";
} else {
echo "Error creating database: " . mysqli_error($conn);
// closing connection
mysqli_close($conn);
?>
MySQLi Object-oriented procedure::
To close the connection in mysql database we use php function
conn->close() which disconnect from database.
Syntax:
conn->close();
Program: To illustrate the closing of connection in object-oriented
procedure.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "newDB";
// checking connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
//Close the connection
$conn->close();
?>