PHP 7 (1203)
PHP 7 (1203)
PHP 7 (1203)
local
global
static
Example:
<?php
$x = 5; // global scope
function myTest() {
// using x inside this function will generate an error
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
echo "<p>Variable x outside function is: $x</p>";
?>
A variable declared within a function has a LOCAL SCOPE and can only be accessed within that function:
Example:
<?php
function myTest() {
$x = 5; // local scope
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
// using x outside the function will generate an error
echo "<p>Variable x outside function is: $x</p>";
?>
You can have local variables with the same name in different functions, because local variables are only recognized by
the function in which they are declared.
Example:
<?php
$x = 5;
$y = 10;
function myTest() {
global $x, $y;
$y = $x + $y;
}
myTest();
echo $y; // outputs 15
?>
PHP also stores all global variables in an array called $GLOBALS[index]. The index holds the name of the variable. This
array is also accessible from within functions and can be used to update global variables directly.
The example above can be rewritten like this:
Example:
<?php
$x = 5;
$y = 10;
function myTest() {
$GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
}
myTest();
echo $y; // outputs 15
?>
Example:
<?php
function myTest() {
static $x = 0;
echo $x;
$x++;
}
myTest();
myTest();
myTest();
?>
Then, each time the function is called, that variable will still have the information it contained from the last time the
function was called.
Display Text
The following example shows how to output text with the echo command (notice that the text can contain HTML markup):
Example:
<?php
echo "<h2>PHP is Fun!</h2>";
echo "Hello world!<br>";
echo "I'm about to learn PHP!<br>";
echo "This ", "string ", "was ", "made ", "with multiple parameters.";
?>
Display Variables
The following example shows how to output text and variables with the echo statement:
Example:
<?php
$txt1 = "Learn PHP";
$txt2 = "W3Schools.com";
$x = 5;
$y = 4;
Display Text
The following example shows how to output text with the print command (notice that the text can contain HTML markup):
Example:
<?php
print "<h2>PHP is Fun!</h2>";
print "Hello world!<br>";
print "I'm about to learn PHP!";
?>
Display Variables
The following example shows how to output text and variables with the print statement:
Example:
<?php
$txt1 = "Learn PHP";
$txt2 = "W3Schools.com";
$x = 5;
$y = 4;
String
Integer
Float (floating point numbers - also called double)
Boolean
Array
Object
NULL
Resource
PHP Object
An object is a data type which stores data and information on how to process that data.
In PHP, an object must be explicitly declared.
First we must declare a class of object. For this, we use the class keyword. A class is a structure that can contain properties
and methods:
Example:
<?php
class Car {
function Car() {
$this->model = "VW";
}
}
// create an object
$herbie = new Car();
Example:
<?php
$x = "Hello world!";
$x = null;
var_dump($x);
?>
PHP Resource
The special resource type is not an actual data type. It is the storing of a reference to functions and resources external to
PHP.
A common example of using the resource data type is a database call.
We will not talk about the resource type here, since it is an advanced topic.
PHP Constants
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)
Parameters:
name: Specifies the name of the constant
value: Specifies the value of the constant
case-insensitive: Specifies whether the constant name should be case-insensitive. Default is false
Example:
<?php
define("GREETING", "Welcome to W3Schools.com!");
echo GREETING;
?>
Example:
<?php
define("GREETING", "Welcome to W3Schools.com!", true);
echo greeting;
?>
Example:
<?php
define("cars", [
"Alfa Romeo",
"BMW",
"Toyota"
]);
echo cars[0];
?>
Constants are Global
Constants are automatically global and can be used across the entire script.
The example below uses a constant inside a function, even if it is defined outside the function:
Example:
<?php
define("GREETING", "Welcome to W3Schools.com!");
function myTest() {
echo GREETING;
}
myTest();
?>
The real power of PHP comes from its functions; it has more than 1000 built-in functions.
PHP User Defined Functions
Besides the built-in PHP functions, we can create our own functions.
A function is a block of statements that can be used repeatedly in a program.
A function will not execute immediately when a page loads.
A function will be executed by a call to the function.
Syntax:
function functionName() {
code to be executed;
}
Note: A function name can start with a letter or underscore (not a number).
Tip: Give the function a name that reflects what the function does!
In the example below, we create a function named "writeMsg()". The opening curly brace ( { ) indicates the beginning of
the function code, and the closing curly brace ( } ) indicates the end of the function. The function outputs "Hello world!". To call
the function, just write its name followed by brackets ():
Example:
<?php
function writeMsg() {
echo "Hello world!";
}
Example:
<?php
function familyName($fname) {
echo "$fname Refsnes.<br>";
}
familyName("Jani");
familyName("Hege");
familyName("Stale");
familyName("Kai Jim");
familyName("Borge");
?>
The following example has a function with two arguments ($fname and $year):
Example:
<?php
familyName("Hege", "1975");
familyName("Stale", "1978");
familyName("Kai Jim", "1983");
?>
In the following example we try to add a number and a string with without the strict requirement:
Example:
<?php
In the following example we try to add a number and a string with with the strict requirement:
Example:
<?php
declare(strict_types=1); // strict requirement
To specify strict we need to set declare(strict_types=1);. This must be the on the very first line of the PHP file. Declaring
strict specifies that function calls made in that file must strictly adhere to the specified data types
The strict declaration can make code easier to read, and it forces things to be used in the intended way.
Going forward in this tutorial, we will use the strict requirement.
PHP Default Argument Value
The following example shows how to use a default parameter. If we call the function setHeight() without arguments it
takes the default value as argument:
Example:
<?php
declare(strict_types=1); // strict requirement
setHeight(350);
setHeight(); // will use the default value of 50
setHeight(135);
setHeight(80);
?>
Example:
<?php
declare(strict_types=1); // strict requirement
In the following example we specify the return type for the function:
Example:
<?php
declare(strict_types=1); // strict requirement
Example:
<?php
declare(strict_types=1); // strict requirement
Example:
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
What is an Array?
An array is a special variable, which can hold more than one value at a time.
If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this:
$cars1 = "Volvo";
$cars2 = "BMW";
$cars3 = "Toyota";
However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300?
The solution is to create an array!
An array can hold many values under a single name, and you can access the values by referring to an index number.
array();
The index can be assigned automatically (index always starts at 0), like this:
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
The following example creates an indexed array named $cars, assigns three elements to it, and then prints a text
containing the array values:
Example:
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
Example:
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo count($cars);
?>
Example:
<?php
$cars = array("Volvo", "BMW", "Toyota");
$arrlength = count($cars);
or:
$age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";
Example:
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>
Loop Through an Associative Array
To loop through and print all the values of an associative array, you could use a foreach loop, like this:
Example:
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
$GLOBALS
$_SERVER
$_REQUEST
$_POST
$_GET
$_FILES
$_ENV
$_COOKIE
$_SESSION
This chapter will explain some of the superglobals, and the rest will be explained in later chapters.
PHP $GLOBALS
$GLOBALS is a PHP super global variable which is used to access global variables from anywhere in the PHP script (also
from within functions or methods).
PHP stores all global variables in an array called $GLOBALS[index]. The index holds the name of the variable.
The example below shows how to use the super global variable $GLOBALS:
Example:
<?php
$x = 75;
$y = 25;
function addition() {
$GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
}
addition();
echo $z;
?>
In the example above, since z is a variable present within the $GLOBALS array, it is also accessible from outside the
function!
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:
Example:
<?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'];
?>
The following table lists the most important elements that can go inside $_SERVER:
Element/Code Description
$_SERVER['PHP_SELF'] Returns the filename of the currently executing script
$_SERVER['GATEWAY_INTERFACE'] Returns the version of the Common Gateway Interface (CGI) the server is using
$_SERVER['SERVER_ADDR'] Returns the IP address of the host server
$_SERVER['SERVER_NAME'] Returns the name of the host server (such as www.w3schools.com)
$_SERVER['SERVER_SOFTWARE'] Returns the server identification string (such as Apache/2.2.24)
$_SERVER['SERVER_PROTOCOL' ] Returns the name and revision of the information protocol (such as HTTP/1.1)
$_SERVER['REQUEST_METHOD'] Returns the request method used to access the page (such as POST)
$_SERVER['REQUEST_TIME'] Returns the timestamp of the start of the request (such as 1377687496)
$_SERVER['QUERY_STRING'] Returns the query string if the page is accessed via a query string
$_SERVER['HTTP_ACCEPT'] Returns the Accept header from the current request
$_SERVER['HTTP_ACCEPT_CHARSET'] Returns the Accept_Charset header from the current request (such as utf-8,ISO-8859-1)
$_SERVER['HTTP_HOST'] Returns the Host header from the current request
$_SERVER['HTTP_REFERER'] Returns the complete URL of the current page (not reliable because not all user-agents support it)
$_SERVER['HTTPS'] Is the script queried through a secure HTTP protocol
$_SERVER['REMOTE_ADDR'] Returns the IP address from where the user is viewing the current page
$_SERVER['REMOTE_HOST'] Returns the Host name from where the user is viewing the current page
$_SERVER['REMOTE_PORT'] Returns the port being used on the user's machine to communicate with the web server
$_SERVER['SCRIPT_FILENAME'] Returns the absolute pathname of the currently executing script
$_SERVER['SERVER_ADMIN'] Returns the value given to the SERVER_ADMIN directive in the web server configuration file (if your script runs on
a virtual host, it will be the value defined for that virtual host) (such as [email protected])
$_SERVER['SERVER_PORT'] Returns the port on the server machine being used by the web server for communication (such as 80)
$_SERVER['SERVER_SIGNATURE'] Returns the server version and virtual host name which are added to server-generated pages
$_SERVER['PATH_TRANSLATED'] Returns the file system based path to the current script
$_SERVER['SCRIPT_NAME'] Returns the path of the current script
$_SERVER['SCRIPT_URI'] Returns the URI of the current page
PHP $_REQUEST
PHP $_REQUEST 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:
Example:
<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 $_POST
PHP $_POST is widely 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:
Example:
<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 $_GET
PHP $_GET can also be 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":
Example:
<html>
<body>
<?php
echo "Study " . $_GET['subject'] . " at " . $_GET['web'];
?>
</body>
</html
PHP 7 FORM HANDLING
Tip: You will learn more about $_POST and $_GET in the PHP Forms chapter.
The PHP superglobals $_GET and $_POST are used to collect form-data.
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>
Welcome John
Your email address is [email protected]
The same result could also be achieved using the HTTP GET method:
Example:
<html>
<body>
<form action="welcome_get.php" method="get">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>
and "welcome_get.php" looks like this:
<html>
<body>
Welcome <?php echo $_GET["name"]; ?><br>
Your email address is: <?php echo $_GET["email"]; ?>
</body>
</html>
The code above is quite simple. However, the most important thing is missing. You need to validate form data to protect
your script from malicious code.
Note: GET should NEVER be used for sending passwords or other sensitive information!
First we will look at the plain HTML code for the form:
Text Fields
The name, email, and website fields are text input elements, and the comment field is a textarea. The HTML code looks
like this:
Radio Buttons
The gender fields are radio buttons and the HTML code looks like this:
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<input type="radio" name="gender" value="other">Other
When the form is submitted, the form data is sent with method="post".
Now, if a user enters the normal URL in the address bar like "http://www.example.com/test_form.php", the above code
will be translated to:
So far, so good.
However, consider that a user enters the following URL in the address bar:
http://www.example.com/test_form.php/%22%3E%3Cscript%3Ealert('hacked')%3C/script%3E
This code adds a script tag and an alert command. And when the page loads, the JavaScript code will be executed (the
user will see an alert box). This is just a simple and harmless example how the PHP_SELF variable can be exploited.
Be aware of that any JavaScript code can be added inside the <script> tag! A hacker can redirect the user to a file on
another server, and that file can hold malicious code that can alter the global variables or submit the form to another address to
save the user data, for example.
The htmlspecialchars() function converts special characters to HTML entities. Now if the user tries to exploit the PHP_SELF
variable, it will result in the following output:
<script>location.href('http://www.hacked.com')</script>
- this would not be executed, because it would be saved as HTML escaped code, like this:
<script>location.href('http://www.hacked.com')</script>
Strip unnecessary characters (extra space, tab, newline) from the user input data (with the PHP trim() function)
Remove backslashes (\) from the user input data (with the PHP stripslashes() function)
The next step is to create a function that will do all the checking for us (which is much more convenient than writing the same
code over and over again).
We will name the function test_input().
Now, we can check each $_POST variable with the test_input() function, and the script looks like this:
Example:
<?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$website = test_input($_POST["website"]);
$comment = test_input($_POST["comment"]);
$gender = test_input($_POST["gender"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
Notice that at the start of the script, we check whether the form has been submitted using
$_SERVER["REQUEST_METHOD"]. If the REQUEST_METHOD is POST, then the form has been submitted - and it should be
validated. If it has not been submitted, skip the validation and display a blank form.
However, in the example above, all input fields are optional. The script works fine even if the user does not enter any
data.
The next step is to make input fields required and create error messages if needed.
This chapter shows how to make input fields required and create error messages if needed.
PHP 7 FORMS - REQUIRED FIELDS
From the validation rules table on the previous page, we see that the "Name", "E-mail", and "Gender" fields are required.
These fields cannot be empty and must be filled out in the HTML form.
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
}
if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
}
?>
PHP - Display The Error Messages
Then in the HTML form, we add a little script after each required field, which generates the correct error message if
needed (that is if the user tries to submit the form without filling out the required fields):
Example:
<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>
E-mail:
<input type="text" name="email">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Website:
<input type="text" name="website">
<span class="error"><?php echo $websiteErr;?></span>
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<br><br>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<input type="radio" name="gender" value="other">Other
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
The next step is to validate the input data, that is "Does the Name field contain only letters and whitespace?", and "Does
the E-mail field contain a valid e-mail address syntax?", and if filled out, "Does the Website field contain a valid URL?".
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
The preg_match() function searches a string for pattern, returning true if the pattern exists, and false otherwise.
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
PHP - Validate URL
The code below shows a way to check if a URL address syntax is valid (this regular expression also allows dashes in the
URL). If the URL address syntax is not valid, then store an error message:
$website = test_input($_POST["website"]);
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
Example:
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
// check if URL address syntax is valid (this regular expression also allows dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-
9+&@#\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
}
?>
The next step is to show how to prevent the form from emptying all the input fields when the user submits the form.
PHP 7 - COMPLETE FORM EXAMPLE
This chapter shows how to keep the values in the input fields when the user hits the submit button.
We can store the data from the table above in a two-dimensional array, like this:
$cars = array
(
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
Now the two-dimensional $cars array contains four arrays, and it has two indices: row and column.
To get access to the elements of the $cars array we must point to the two indices (row and column):
Example:
<?php
echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".<br>";
echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2].".<br>";
echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2][2].".<br>";
echo $cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3][2].".<br>";
?>
We can also put a for loop inside another for loop to get the elements of the $cars array (we still have to point to the two
indices):
Example:
<?php
for ($row = 0; $row < 4; $row++) {
echo "<p><b>Row number $row</b></p>";
echo "<ul>";
for ($col = 0; $col < 3; $col++) {
echo "<li>".$cars[$row][$col]."</li>";
}
echo "</ul>";
}
?>
PHP 7 INCLUDE FILES
The include (or require) statement takes all the text/code/markup that exists in the specified file and copies it into the
file that uses the include statement.
Including files is very useful when you want to include the same PHP, HTML, or text on multiple pages of a website.
require will produce a fatal error (E_COMPILE_ERROR) and stop the script
include will only produce a warning (E_WARNING) and the script will continue
So, if you want the execution to go on and show users the output, even if the include file is missing, use the include
statement. Otherwise, in case of FrameWork, CMS, or a complex PHP application coding, always use the require statement to
include a key file to the flow of execution. This will help avoid compromising your application's security and integrity, just in-case
one key file is accidentally missing.
Including files saves a lot of work. This means that you can create a standard header, footer, or menu file for all your web
pages. Then, when the header needs to be updated, you can only update the header include file.
Syntax
include 'filename';
or
require 'filename';
Example 1
Assume we have a standard footer file called "footer.php", that looks like this:
<?php
echo "<p>Copyright © 1999-" . date("Y") . " W3Schools.com</p>";
?>
Example:
<html>
<body>
<h1>Welcome to my home page!</h1>
<p>Some text.</p>
<p>Some more text.</p>
<?php include 'footer.php';?>
</body>
</html>
Example 2
Assume we have a standard menu file called "menu.php":
<?php
echo '<a href="/default.asp">Home</a> -
<a href="/html/default.asp">HTML Tutorial</a> -
<a href="/css/default.asp">CSS Tutorial</a> -
<a href="/js/default.asp">JavaScript Tutorial</a> -
<a href="default.asp">PHP Tutorial</a>';
?>
All pages in the Web site should use this menu file. Here is how it can be done (we are using a <div> element so that the
menu easily can be styled with CSS later):
Example:
<html>
<body>
<div class="menu">
<?php include 'menu.php';?>
</div>
<h1>Welcome to my home page!</h1>
<p>Some text.</p>
<p>Some more text.</p>
</body>
</html
Example 3
Assume we have a file called "vars.php", with some variables defined:
<?php
$color='red';
$car='BMW';
?>
Then, if we include the "vars.php" file, the variables can be used in the calling file:
Example:
<html>
<body>
<h1>Welcome to my home page!</h1>
<?php include 'vars.php';
echo "I have a $color $car.";
?>
</body>
</html>
Example:
<html>
<body>
<h1>Welcome to my home page!</h1>
<?php include 'noFileExists.php';
echo "I have a $color $car.";
?>
</body>
</html>
If we do the same example using the require statement, the echo statement will not be executed because the script
execution dies after the require statement returned a fatal error:
Example:
<html>
<body>
<h1>Welcome to my home page!</h1>
<?php require 'noFileExists.php';
echo "I have a $color $car.";
?>
</body>
</html>
The PHP code to read the file and write it to the output buffer is as follows (the readfile() function returns the number of
bytes read on success):
Example:
<?php
echo readfile("webdictionary.txt");
?>
The readfile() function is useful if all you want to do is open up a file and read its contents.
The next chapters will teach you more about file handling.
The first parameter of fopen() contains the name of the file to be opened and the second parameter specifies in which
mode the file should be opened. The following example also generates a message if the fopen() function is unable to open the
specified file:
Example:
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
echo fread($myfile,filesize("webdictionary.txt"));
fclose($myfile);
?>
Tip: The fread() and the fclose() functions will be explained below.
The file may be opened in one of the following modes:
Modes Description
r Open a file for read only. File pointer starts at the beginning of the file
w Open a file for write only. Erases the contents of the file or creates a new file if it doesn't exist. File pointer starts at the beginning of the file
a Open a file for write only. The existing data in file is preserved. File pointer starts at the end of the file. Creates a new file if the file doesn't exist
x Creates a new file for write only. Returns FALSE and an error if file already exists
r+ Open a file for read/write. File pointer starts at the beginning of the file
w+ Open a file for read/write. Erases the contents of the file or creates a new file if it doesn't exist. File pointer starts at the beginning of the file
a+ Open a file for read/write. The existing data in file is preserved. File pointer starts at the end of the file. Creates a new file if the file doesn't exist
x+ Creates a new file for read/write. Returns FALSE and an error if file already exists
fread($myfile,filesize("webdictionary.txt"));
<?php
$myfile = fopen("webdictionary.txt", "r");
// some code to be executed....
fclose($myfile);
?>
Example:
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
echo fgets($myfile);
fclose($myfile);
?>
Note: After a call to the fgets() function, the file pointer has moved to the next line.
PHP Check End-Of-File - feof()
The feof() function checks if the "end-of-file" (EOF) has been reached.
The feof() function is useful for looping through data of unknown length.
The example below reads the "webdictionary.txt" file line by line, until end-of-file is reached:
Example:
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
// Output one line until end-of-file
while(!feof($myfile)) {
echo fgets($myfile) . "<br>";
}
fclose($myfile);
?>
Example:
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
// Output one character until end-of-file
while(!feof($myfile)) {
echo fgetc($myfile);
}
fclose($myfile);
?>
Note: After a call to the fgetc() function, the file pointer moves to the next character.
Example:
$myfile = fopen("testfile.txt", "w")
Example:
<?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "John Doe\n";
fwrite($myfile, $txt);
$txt = "Jane Doe\n";
fwrite($myfile, $txt);
fclose($myfile);
?>
Notice that we wrote to the file "newfile.txt" twice. Each time we wrote to the file we sent the string $txt that first
contained "John Doe" and second contained "Jane Doe". After we finished writing, we closed the file using the fclose() function.
If we open the "newfile.txt" file it would look like this:
John Doe
Jane Doe
PHP Overwriting
Now that "newfile.txt" contains some data we can show what happens when we open an existing file for writing. All the
existing data will be ERASED and we start with an empty file.
In the example below we open our existing file "newfile.txt", and write some new data into it:
Example:
<?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "Mickey Mouse\n";
fwrite($myfile, $txt);
$txt = "Minnie Mouse\n";
fwrite($myfile, $txt);
fclose($myfile);
?>
If we now open the "newfile.txt" file, both John and Jane have vanished, and only the data we just wrote is present:
Mickey Mouse
Minnie Mouse
file_uploads = On
Create The HTML Form
Next, create an HTML form that allow users to choose the image file they want to upload:
<!DOCTYPE html>
<html>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
?>
$target_dir = "uploads/" - specifies the directory where the file is going to be placed
$target_file specifies the path of the file to be uploaded
$uploadOk=1 is not used yet (will be used later)
$imageFileType holds the file extension of the file (in lower case)
Next, check if the image file is an actual image or a fake image
Note: You will need to create a new directory called "uploads" in the directory where "upload.php" file resides. The uploaded files
will be saved there.
Check if File Already Exists
Now we can add some restrictions.
First, we will check if the file already exists in the "uploads" folder. If it does, an error message is displayed, and $uploadOk
is set to 0:
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
PHP 7 - COOKIES
A cookie is often used to identify a user.
What is a Cookie?
A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer. Each time
the same computer requests a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie
values.
Syntax
setcookie(name, value, expire, path, domain, secure, httponly);
Only the name parameter is required. All other parameters are optional.
Example:
<?php
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>
Note: The setcookie() function must appear BEFORE the <html> tag.
Note: The value of the cookie is automatically URLencoded when sending the cookie, and automatically decoded when
received (to prevent URLencoding, use setrawcookie() instead).
Modify a Cookie Value
To modify a cookie, just set (again) the cookie using the setcookie() function:
Example:
<?php
$cookie_name = "user";
$cookie_value = "Alex Porter";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>
Delete a Cookie
To delete a cookie, use the setcookie() function with an expiration date in the past:
Example:
<?php
// set the expiration date to one hour ago
setcookie("user", "", time() - 3600);
?>
<html>
<body>
<?php
echo "Cookie 'user' is deleted.";
?>
</body>
</html>
Example
<?php
setcookie("test_cookie", "test", time() + 3600, '/');
?>
<html>
<body>
<?php
if(count($_COOKIE) > 0) {
echo "Cookies are enabled.";
} else {
echo "Cookies are disabled.";
}
?>
</body>
</html>
A session is a way to store information (in variables) to be used across multiple pages.
Unlike a cookie, the information is not stored on the users computer.
PHP 7 - SESSIONS
What is a PHP Session?
When you work with an application, you open it, do some changes, and then you close it. This is much like a Session. The
computer knows who you are. It knows when you start the application and when you end. But on the internet there is one
problem: the web server does not know who you are or what you do, because the HTTP address doesn't maintain state.
Session variables solve this problem by storing user information to be used across multiple pages (e.g. username, favorite
color, etc). By default, session variables last until the user closes the browser.
So; Session variables hold information about one single user, and are available to all pages in one application.
Tip: If you need a permanent storage, you may want to store the data in a database.
Example:
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>
</body>
</html>
Note: The session_start() function must be the very first thing in your document. Before any HTML tags.
Example:
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Echo session variables that were set on previous page
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>
</body>
</html>
Another way to show all the session variable values for a user session is to run the following code:
Example:
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
print_r($_SESSION);
?>
</body>
</html>
Example:
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// to change a session variable, just overwrite it
$_SESSION["favcolor"] = "yellow";
print_r($_SESSION);
?>
</body>
</html>
Example:
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// remove all session variables
session_unset();
// destroy the session
session_destroy();
?>
</body>
</html>
PHP 7 - FILTERS
Validating data = Determine if the data is in proper form.
Sanitizing data = Remove any illegal character from the data.
Example:
<table>
<tr>
<td>Filter Name</td>
<td>Filter ID</td>
</tr>
<?php
foreach (filter_list() as $id =>$filter) {
echo '<tr><td>' . $filter . '</td><td>' . filter_id($filter) . '</td></tr>';
}
?>
</table>
The following example uses the filter_var() function to remove all HTML tags from a string:
Example:
<?php
$str = "<h1>Hello World!</h1>";
$newstr = filter_var($str, FILTER_SANITIZE_STRING);
echo $newstr;
?>
Validate an Integer
The following example uses the filter_var() function to check if the variable $int is an integer. If $int is an integer, the
output of the code below will be: "Integer is valid". If $int is not an integer, the output will be: "Integer is not valid":
Example
<?php
$int = 100;
if (!filter_var($int, FILTER_VALIDATE_INT) === false) {
echo("Integer is valid");
} else {
echo("Integer is not valid");
}
?>
Example:
<?php
$int = 0;
if (filter_var($int, FILTER_VALIDATE_INT) === 0 || !filter_var($int, FILTER_VALIDATE_INT) === false) {
echo("Integer is valid");
} else {
echo("Integer is not valid");
}
?>
Validate an IP Address
The following example uses the filter_var() function to check if the variable $ip is a valid IP address:
Example:
<?php
$ip = "127.0.0.1";
if (!filter_var($ip, FILTER_VALIDATE_IP) === false) {
echo("$ip is a valid IP address");
} else {
echo("$ip is not a valid IP address");
}
?>
Example:
<?php
$email = "[email protected]";
// Validate e-mail
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
echo("$email is a valid email address");
} else {
echo("$email is not a valid email address");
}
?>
Sanitize and Validate a URL
The following example uses the filter_var() function to first remove all illegal characters from a URL, then check if $url is
a valid URL:
Example:
<?php
$url = "https://www.w3schools.com";
// Remove all illegal characters from a url
$url = filter_var($url, FILTER_SANITIZE_URL);
// Validate url
if (!filter_var($url, FILTER_VALIDATE_URL) === false) {
echo("$url is a valid URL");
} else {
echo("$url is not a valid URL");
}
?>
Example:
<?php
$int = 122;
$min = 1;
$max = 200;
if (filter_var($int, FILTER_VALIDATE_INT, array("options" => array("min_range"=>$min, "max_range"=>$max))) ===
false) {
echo("Variable value is not within the legal range");
} else {
echo("Variable value is within the legal range");
}
?>
Example:
<?php
$ip = "2001:0db8:85a3:08d3:1319:8a2e:0370:7334";
if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) === false) {
echo("$ip is a valid IPv6 address");
} else {
echo("$ip is not a valid IPv6 address");
}
?>
Example:
<?php
$url = "https://www.w3schools.com";
Example:
<?php
$str = "<h1>Hello WorldÆØÅ!</h1>";
$newstr = filter_var($str, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
echo $newstr;
?>
PHP 7 - MYSQL DATABASE
With PHP, you can connect to and manipulate databases.
MySQL is the most popular database system used with PHP.
What is MySQL?
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.
Databases are useful for storing information categorically. A company may have a database with the following tables:
Employees
Products
Customers
Orders
The query above selects all the data in the "LastName" column from the "Employees" table.
To learn more about SQL, please visit our SQL tutorial.
Earlier versions of PHP used the MySQL extension. However, this extension was deprecated in 2012.
MySQLi (object-oriented)
MySQLi (procedural)
PDO
MySQLi Installation
For Linux and Windows: The MySQLi extension is automatically installed in most cases, when php5 mysql package is
installed.
For installation details, go to: http://php.net/manual/en/mysqli.installation.php
PDO Installation
For installation details, go to: http://php.net/manual/en/pdo.installation.php
// Check connection
if (mysqli_connect_error()) {
die("Database connection failed: " . mysqli_connect_error());
}
Example (PDO):
<?php
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
Note: In the PDO example above we have also specified a database (myDB). PDO require a valid database to connect to.
If no database is specified, an exception is thrown.
Tip: A great benefit of PDO is that it has an exception class to handle any problems that may occur in our database queries.
If an exception is thrown within the try{ } block, the script stops executing and flows directly to the first catch(){ } block.
Example (PDO):
$conn = null;
PHP 7 - CREATE A MYSQL DATABASE
A database consists of one or more tables.
You will need special CREATE privileges to create or to delete a MySQL database.
Note: When you create a new database, you must only specify the first three arguments to the mysqli object (servername,
username and password).
Tip: If you have to use a specific port, add an empty string for the database-name argument, like this: new
mysqli("localhost", "username", "password", "", port)
Example (PDO):
<?php
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "CREATE DATABASE myDBPDO";
// use exec() because no results are returned
$conn->exec($sql);
echo "Database created successfully<br>";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
Tip: A great benefit of PDO is that it has exception class to handle any problems that may occur in our database queries.
If an exception is thrown within the try{ } block, the script stops executing and flows directly to the first catch(){ } block. In the
catch block above we echo the SQL statement and the generated error message.
NOT NULL - Each row must contain a value for that column, null values are not allowed
DEFAULT value - Set a default value that is added when no other value is passed
UNSIGNED - Used for number types, limits the stored data to positive numbers and zero
AUTO INCREMENT - MySQL automatically increases the value of the field by 1 each time a new record is added
PRIMARY KEY - Used to uniquely identify the rows in a table. The column with PRIMARY KEY setting is often an ID
number, and is often used with AUTO_INCREMENT
Each table should have a primary key column (in this case: the "id" column). Its value must be unique for each record in
the table.
The following examples shows how to create the table in PHP:
Note: If a column is AUTO_INCREMENT (like the "id" column) or TIMESTAMP with default update of current_timesamp
(like the "reg_date" column), it is no need to be specified in the SQL query; MySQL will automatically add the value.
Example (PDO):
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', '[email protected]')";
// use exec() because no results are returned
$conn->exec($sql);
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
Example (PDO):
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', '[email protected]')";
// use exec() because no results are returned
$conn->exec($sql);
$last_id = $conn->lastInsertId();
echo "New record created successfully. Last inserted ID is: " . $last_id;
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
Example (PDO):
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// begin the transaction
$conn->beginTransaction();
// our SQL statements
$conn->exec("INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', '[email protected]')");
$conn->exec("INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('Mary', 'Moe', '[email protected]')");
$conn->exec("INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('Julie', 'Dooley', '[email protected]')");
// commit the transaction
$conn->commit();
echo "New records created successfully";
}
catch(PDOException $e)
{
// roll back the transaction if something failed
$conn->rollback();
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
Prepare: An SQL statement template is created and sent to the database. Certain values are left unspecified, called
parameters (labeled "?"). Example: INSERT INTO MyGuests VALUES(?, ?, ?)
The database parses, compiles, and performs query optimization on the SQL statement template, and stores the result
without executing it
Execute: At a later time, the application binds the values to the parameters, and the database executes the statement.
The application may execute the statement as many times as it wants with different values
Compared to executing SQL statements directly, prepared statements have three main advantages:
Prepared statements reduce parsing time as the preparation on the query is done only once (although the statement is
executed multiple times)
Bound parameters minimize bandwidth to the server as you need send only the parameters each time, and not the whole
query
Prepared statements are very useful against SQL injections, because parameter values, which are transmitted later using
a different protocol, need not be correctly escaped. If the original statement template is not derived from external input,
SQL injection cannot occur.
Prepared Statements in MySQLi
The following example uses prepared statements and bound parameters in MySQLi:
This function binds the parameters to the SQL query and tells the database what the parameters are. The "sss" argument
lists the types of data that the parameters are. The s character tells mysql that the parameter is a string.
i - integer
d - double
s - string
b – BLOB
Note: If we want to insert any data from external sources (like user input), it is very important that the data is sanitized
and validated.
Prepared Statements in PDO
The following example uses prepared statements and bound parameters in PDO:
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.
The following example shows the same as the example above, in the MySQLi procedural way:
Example (PDO):
<?php
echo "<table style='border: solid 1px black;'>";
echo "<tr><th>Id</th><th>Firstname</th><th>Lastname</th></tr>";
function current() {
return "<td style='width:150px;border:1px solid black;'>" . parent::current(). "</td>";
}
function beginChildren() {
echo "<tr>";
}
function endChildren() {
echo "</tr>" . "\n";
}
}
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT id, firstname, lastname FROM MyGuests");
$stmt->execute();
Notice the WHERE clause in the DELETE syntax: The WHERE clause specifies which record or records that should be
deleted. If you omit the WHERE clause, all records will be deleted!
To learn more about SQL, please visit our SQL tutorial.
The following examples delete the record with id=3 in the "MyGuests" table:
Example (PDO):
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// sql to delete a record
$sql = "DELETE FROM MyGuests WHERE id=3";
// use exec() because no results are returned
$conn->exec($sql);
echo "Record deleted successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
After the record is deleted, the table will look like this:
UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value
Notice the WHERE clause in the UPDATE syntax: The WHERE clause specifies which record or records that should be
updated. If you omit the WHERE clause, all records will be updated!
To learn more about SQL, please visit our SQL tutorial.
Example (PDO):
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";
// Prepare statement
$stmt = $conn->prepare($sql);
// execute the query
$stmt->execute();
// echo a message to say the UPDATE succeeded
echo $stmt->rowCount() . " records UPDATED successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
After the record is updated, the table will look like this:
id firstname lastname email reg_date
1 John Doe [email protected] 2014-10-22 14:26:15
2 Mary Doe [email protected] 2014-10-23 10:22:30