Introduction to PHP - III

Global Variables:

Several predefined variables in PHP are "superglobals", which means that they are always accessible, regardless of scope - and you can access them from any function, class or file without having to do anything special. The PHP superglobal variables are:

Some of the PHP superglobal variables are:
  • $_SERVER
  • $_REQUEST
  • $_POST
  • $_GET
  • $_FILES
  • $_ENV
  • $_COOKIE
  • $_SESSION
  • $GLOBALS
We'll only study about $_POST and $_GET variables for the time being remaining ones will be discussed later.

GET vs POST

Both GET and POST create an array (e.g. array( key => value, key2 => value2, key3 => value3, ....)). This array holds key/value pairs, where keys are the names of the form controls and values are the input data from the user. 

Both GET and POST is treated as $_GET and $_POST. These are superglobals, which means that they are always accessible, regardless of scope - and you can access them from any function, class or file without having to do anything special. $_GET is an array of variables passed to the current script via the URL parameters, whereas $_POST is an array of variables passed to the current script via the HTTP POST method.

When to use GET?

Information sent from a form with GET method is visible to everyone (all variable names and values are displayed in the URL). GET also has limits on the amount of information to send. The limitation is about 2000 characters. However, because the variables are displayed in the URL, it is possible to bookmark the page. This can be useful in some cases.GET may be used for sending non-sensitive data.

NOTE: GET should NEVER be used for sending passwords or other sensitive information!

When to use POST?

Information sent from a form with the POST method is invisible to others (all names/values are embedded within the body of the HTTP request) and has no limits on the amount of information to send.
However, because the variables are not displayed in the UR, it is not possible to bookmark the page. 

Mostly Developers prefer POST for sending form data.

PHP FORMS:
The PHP superglobals $_GET and $_POST are used to collect form-data.
The example below displays a simple HTML form with two input fields and submit button:

Example:
<form method="$_GET">
         Name: <input type="text" name="name"><br>
         E-mail: <input type="text" name="email"><br>

        <input type="submit">
</form>

The above example will only send the data in the URL but the catch over here is we're not pointing the server where the data should be sent? For this, there's an attribute of the form called the action.

Example:
<html>

<body>



<form action="welcome.php" method="post">

         Name: <input type="text" name="name"><br>
         E-mail: <input type="text" name="email"><br>

         <input type="submit">

</form>



</body>

</html>

When the user fills out the form above and clicks the submit button, the form data is sent for processing to a PHP file named "welcome.php". The form data is sent with the HTTP POST method.
To display the submitted data you could simply echo all the variables. The "welcome.php" looks like this:
<html>
<body>

Welcome <?php echo $_POST["name"]; ?><br>
Your email address is: <?php echo $_POST["email"]; ?>

</body>
</html>
The output could be something like this:
Welcome John
Your email address is john.doe@example.com
Database Connections:
With PHP, you can connect to and manipulate databases, for manipulation MySQL is the most popular database system used in PHP. The data in a MySQL database are stored in tables. A table is a collection of related data, and it consists of columns and rows.
Lets leave the SQL queries for now we'll learn more about it later.
PHP 5 and later can work with a MySQL database using:

  • MySQLi extension (the " i " stands for improved)
  • PDO (PHP Data Objects)
MySQLi or PDO which one to choose?
If you need a short answer, it would be like "Whatever you like". Both MySQLi and PDO have their advantages:
PDO will work on 12 different database systems, whereas MySQLi will only work with MySQL databases. So, if you have to switch your project to use another 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 entire code - quries included. Both are object-oriented, but MySQLi also offers a procedural API. Both of them support Prepared Statements. Prepared statements protect from SQL injection, and are very important for web application security.
Installation:
If you've installed xampp in your computer then you just have to start the mysql from the xampp control panel. It's installed by default with xampp.

Opening a connection to the database:
Before we can access the data in MySQL database, we need to be able to connect to the server.
Example:
<?php
$servername = "localhost";
$username = "username";
$password = "password";

// Create connection$conn = new mysqli($servername, $username, $password);

// Check connectionif ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 
echo "Connected successfully";
?>
Example (Procedural approach):
<?php
$servername = "localhost";
$username = "username";
$password = "password";

// Create connection$conn = mysqli_connect($servername, $username, $password);

// Check connectionif (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>

Now if you've already created a database in your server. You can execute the queries in your php script. If you've any questions regarding MySQL you can watch the following video by Traversy Media:


Inserting Data to the database using PHP:
After a database and a table have been created, we can start adding the data in them. Below are some of the rules to follow while inserting the data.

  • The SQL query must be quoted in PHP
  • String values inside the SQL query must be quoted.
  • Numeric values must not be quoted.
  • The word NULL must not be quoted.
The INSERT INTO statement is used to add new records to a MySQL table:



INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)
Example MySQL Object Oreinted approach:

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection$conn = new mysqli($servername, $username, $password, $dbname);
// Check connectionif ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')"
;

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>

MySQLi Procedural approach:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connectionif (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')"
;

if (mysqli_query($conn, $sql)) {
    echo "New record created successfully";
else {
    echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}

mysqli_close($conn);
?>


Self Study Topics:
  • PHP Arrays
  • Form Validation
  • PHP Required Fields
  • PHP Form URL/Email
  • PHP Form Complete
  • Database Queries

No comments:

Post a Comment