PHP Module
PHP Module
PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web
pages.
PHP is a widely-used, free, and efficient alternative to competitors such as Microsoft's ASP.
Example
<!DOCTYPE html>
<html>
<body>
<?php
echo "My first PHP script!";
?>
</body>
</html>
Before you continue you should have a basic understanding of the following:
HTML
CSS
JavaScript
What is PHP?
It is powerful enough to be at the core of the biggest blogging system on the web (WordPress)!
It is deep enough to run the largest social network (Facebook)!
It is also easy enough to be a beginner's first server side language!
PHP files can contain text, HTML, CSS, JavaScript, and PHP code
PHP code are executed on the server, and the result is returned to the browser as plain
HTML
PHP files have extension ".php"
If your server has activated support for PHP you do not need to do anything.
Just create some .php files, place them in your web directory, and the server will automatically
parse them for you.
PHP script is executed on the server, and the plain HTML result is sent back to the
browser.
<?php
// PHP code goes here
?>
A PHP file normally contains HTML tags, and some PHP scripting code.
Below, we have an example of a simple PHP file, with a PHP script that uses a built-in PHP
function "echo" to output the text "Hello World!" on a web page:
Example
<!DOCTYPE html>
<html>
<body>
<?php
echo "Hello World!";
?>
</body>
</html>
PHP Variables
In PHP, a variable starts with the $ sign, followed by the name of the variable:
<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
?>
A variable can have a short name (like x and y) or a more descriptive name (age, carname,
total_volume).
A variable starts with the $ sign, followed by the name of the variable
A variable name must start with a letter or the underscore character
A variable name cannot start with a number
A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9,
and _ )
Variable names are case-sensitive ($age and $AGE are two different variables)
In PHP there are two basic ways to get output: echo and print.
echo and print are more or less the same. They are both used to output data to the screen.
The differences are small: echo has no return value while print has a return value of 1 so it can be
used in expressions. echo can take multiple parameters (although such usage is rare)
while print can take one argument. echo is marginally faster than print.
Variables can store data of different types, and different data types can do different things.
PHP supports the following data types:
String
Integer
Float (floating point numbers - also called double)
Boolean
Array
Object
NULL
Resource
The example below returns the length of the string "Hello world!":
A constant is an identifier (name) for a simple value. The value cannot be changed during the
script.
A valid constant name starts with a letter or underscore (no $ sign before the constant name).
Note: Unlike variables, constants are automatically global across the entire script.
Syntax
define(name, value, case-insensitive)
define("GREETING", "Welcome to W3Schools.com!");
echo GREETING;
PHP Operators
Arithmetic operators
Assignment operators
Comparison operators
Increment/Decrement operators
Logical operators
String operators
Array operators
Very often when you write code, you want to perform different actions for different conditions.
You can use conditional statements in your code to do this.
The switch statement is used to perform different actions based on different conditions.
PHP Loops
Often when you write code, you want the same block of code to run over and over again in a
row. Instead of adding several almost equal code-lines in a script, we can use loops to perform a
task like this.
while - loops through a block of code as long as the specified condition is true
do...while - loops through a block of code once, and then repeats the loop as long as the
specified condition is true
for - loops through a block of code a specified number of times
foreach - loops through a block of code for each element in an array
The foreach loop works only on arrays, and is used to loop through each key/value pair in an
array.
<?php
$colors = array("red", "green", "blue", "yellow");
Besides the built-in PHP functions, we can create our own functions.
Syntax // similar to c
function functionName() {
code to be executed;
}
Create an Array in PHP
The index can be assigned automatically (index always starts at 0), like this:
The count() function is used to return the length (the number of elements) of an array:
To loop through and print all the values of an indexed array, you could use a for loop, like this:
<?php
$cars = array("Volvo", "BMW", "Toyota");
$arrlength = count($cars);
Associative arrays are arrays that use named keys that you assign to them.
To loop through and print all the values of an associative array, you could use a foreach loop,
like this:
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
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.
$GLOBALS
$_SERVER
$_REQUEST
$_POST
$_GET
$_FILES
$_ENV
$_COOKIE
$_SESSION
HTML Form Handling
sample.html
<html>
<body>
<form action="one.php" method="get">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>
one.php
<html>
<body>
Welcome <?php echo $_GET["name"]; ?><br>
Your email address is: <?php echo $_GET["email"]; ?>
</body>
</html>
Welcome marimuthu
Your email address is: 123
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST["name"];
$email = $_POST["email"];
$website = $_POST["website"];
$comment = $_POST["comment"];
$gender = $_POST["gender"];
}
?>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>
</body>
</html> //output refer complete form validation
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = $passErr = "";
$name = $pass = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = $_POST["name"];
}
if (empty($_POST["pass"])) {
$passErr = "Passord is required";
} else {
$pass = $_POST["pass"];
}
}
?>
<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
Password: <input type="text" name="pass">
<span class="error">* <?php echo $passErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $pass;
?>
</body>
</html>
PHP Complete Form Validation
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST["name"];
$email = $_POST["email"];
$website = $_POST["website"];
$comment = $_POST["comment"];
$gender = $_POST["gender"];
}
?>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>
</body>
</html>
PHP Database Connectivity
<?php
$servername = "localhost:3306";
$username = "root";
$password = "";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
PHP Database Create & Sample Query for [insert,delete & Update]
<?php
$servername = "localhost:3306";
$username = "root";
$password = "";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Create database
$sql = "CREATE DATABASE Employee";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}
$conn->close(); // Connection close
?>
/*
Create Table
Insert Quesry
$sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe',
'[email protected]')";
Insert Multiple Quesry
$sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe',
'[email protected]');";
$sql .= "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('Mary', 'Moe',
'[email protected]');";
$sql .= "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('Julie', 'Dooley',
'[email protected]')";
multi_query($sql)
Delete Query & Update Query
*/
PHP – Database select query
<!DOCTYPE html>
<html>
<?php
$servername = "localhost:3306";
$username = "root";
$password = "";
$dbname = "studentdata";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($result->num_rows > 0) {
echo "<table><tr><th>Name</th><th>ID</th><th>Dept</th><th>College</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["sname"].$row["sno"].$row["sdept"].$row["scollege"]."</td><td>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = $passErr = "";
$name = $pass = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = $_POST["name"];
}
if (empty($_POST["pass"])) {
$passErr = "Passord is required";
} else {
$pass = $_POST["pass"];
}
}
?>
<?php
$servername = "localhost:3306";
$username = "root";
$password = "";
$dbname = "studentdata";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->close();
?>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $pass;
?>
</body>
</html>