PHP Tutorial

You might also like

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 10

What you should already know?

You have to
HTML
JavaScript

have good knowledge of the following before you can proceed:

Whats PHP?
PHP stands for Hypertext Preprocessor.
PHP scripts run inside Apache server or Microsoft IIS.
PHP and Apache server are free.
PHP code is very easy.
PHP is the most used server side scripting language.
PHP files contain PHP scripts and HTML.
PHP files have the extension php, php3, php4, or

phtml.

Whats the difference between PHP and HTML?


HTML files are requested by browser, and returned by server.
PHP files are requested by browser, and executed by the server

to output a plain HTML that is

returned to the browser.


When to use PHP?
Creating Web pages that contain
esponding to HTML forms.
Accessing databases.
Securing data.

dynamic contents.

What makes PHP a choice among the other languages?


PHP is easy to learn.
PHP is free.
PHP can run on Windows
PHP is very fast.

and Unix servers.

Basic PHP Syntax


A PHP script can be placed anywhere in the document.
A PHP script starts with <?php and ends with ?>:
<?php
// PHP code goes here
?>
The default file extension for PHP files is ".php".
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>
<h1>My first PHP page</h1>
<?php
echo "Hello World!";
?>
</body>
</html>
PHP Variables
As with algebra, PHP variables can be used to hold values (x=5) or expressions (z=x+y).
A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume).
Rules for PHP variables:

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 ($y and $Y are two different variables)

PHP echo and print Statements


There are some differences between echo and print:

echo - can output one or more strings


print - can only output one string, and returns always 1

Tip: echo is marginally faster compared to print as echo does not return any value.

The PHP echo Statement


echo is a language construct, and can be used with or without parentheses: echo or echo().
Display Strings
The following example shows how to display different strings with the echo command (also notice that the
strings 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.";
?>

PHP Strings
A string is a sequence of characters, like "Hello world!".
A string can be any text inside quotes. You can use single or double quotes:
Example
<?php
$x = "Hello world!";
echo $x;
echo "<br>";
$x = 'Hello world!';
echo $x;
?>
PHP String Functions
In this chapter we will look at some commonly used functions to manipulate strings.

The PHP strlen() function


The strlen() function returns the length of a string, in characters.
The example below returns the length of the string "Hello world!":
Example
<?php
echo strlen("Hello world!");
?>
The output of the code above will be: 12
Tip: strlen() is often used in loops or other functions, when it is important to know when a string ends. (i.e.
in a loop, we might want to stop the loop after the last character in a string).

The PHP strpos() function


The strpos() function is used to search for a specified character or text within a string.
If a match is found, it will return the character position of the first match. If no match is found, it will
return FALSE.
The example below searches for the text "world" in the string "Hello world!":
Example
<?php
echo strpos("Hello world!","world");
?>
The output of the code above will be: 6.

Tip: The position of the string "world" in the example above is 6. The reason that it is 6 (and not 7), is that
the first character position in the string is 0, and not 1.
PHP Conditional Statements
Very often when you write code, you want to perform different actions for different decisions. You can use
conditional statements in your code to do this.
In PHP we have the following conditional statements:

if statement - executes some code only if a specified condition is true


if...else statement - executes some code if a condition is true and another code if the condition is
false
if...elseif....else statement - selects one of several blocks of code to be executed
switch statement - selects one of many blocks of code to be executed

PHP - The if Statement


The if statement is used to execute some code only if a specified condition is true.
Syntax
if (condition)
{
code to be executed if condition is true;
}
The example below will output "Have a good day!" if the current time (HOUR) is less than 20:
Example
<?php
$t=date("H");
if ($t<"20")
{
echo "Have a good day!";
}
?>

PHP - The if...else Statement


Use the if....else statement to execute some code if a condition is true and another code if the condition
is false.
Syntax
if (condition)
{
code to be executed if condition is true;
}
else
{

code to be executed if condition is false;


}
The example below will output "Have a good day!" if the current time is less than 20, and "Have a good
night!" otherwise:
Example
<?php
$t=date("H");
if ($t<"20")
{
echo "Have a good day!";
}
else
{
echo "Have a good night!";
}
?>
PHP - The if...elseif....else Statement
Use the if....elseif...else statement to select one of several blocks of code to be executed.
Syntax
if (condition)
{
code to be executed if condition is true;
}
elseif (condition)
{
code to be executed if condition is true;
}
else
{
code to be executed if condition is false;
}
The example below will output "Have a good morning!" if the current time is less than 10, and "Have a
good day!" if the current time is less than 20. Otherwise it will output "Have a good night!":
Example
<?php
$t=date("H");
if ($t<"10")
{
echo "Have a good morning!";
}
elseif ($t<"20")
{
echo "Have a good day!";
}
else
{

echo "Have a good night!";


}
?>
PHP Form Handling
The PHP superglobals $_GET and $_POST are used to collect form-data.

PHP - A Simple HTML Form


The example below displays a simple HTML form with two input fields and a submit button:
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
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.
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 are 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.
$_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 the 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.
Moreover POST supports advanced functionality such as support for multi-part binary input while
uploading files to server.

However, because the variables are not displayed in the URL, it is not possible to bookmark the page.
PHP Tutorial : PHP & MySQL
In this PHP Tutorial you will learn about PHP and MySQL - Connecting to MySQL, Closing a connection,
Selecting a database, Executing a query, Inserting data and Retrieving data.
Connecting to MySQL:
To connect to MySQL database server, use the function mysql_connect().
mysql_connect() takes three string arguments, the hostname, the username, and the password.
mysql_connect() returns an integer represents the connection index if the connection is successful, or
returns false if the connection fails.
Example:
<?php
$con = mysql_connect(localhost, john, smith);
echo $con;
?>
Closing a connection:
To close a connection to MySQL, use the function mysql_close().
mysql_close() takes one argument, which is the connection index.
Example:
<?php
$con = mysql_connect(localhost, john, smith);
echo $con;
mysql_close($con);
?>
Selecting a database:
Now you are connected to the MySQL server, to start using queries, you have first to select a database,
because MySQL server can contain many databases.
To select a database, use the function mysql_select_db().
mysql_select_db() takes two arguments, a string represents the database name, and the connection index.
Example:
<?php
$con = mysql_connect(localhost, john, smith);
mysql_select_db(MyDB, $con);
mysql_close($con);
?>
Executing a query:

To execute a SQL query, use the function mysql_query().


mysql_query() takes two arguments, a string represents the SQL statement, and the connection index.
mysql_query() returns a true or false.
Example:
<?php
$con = mysql_connect(localhost, john, smith);
mysql_select_db(MyDB, $con);
$query = SELECT * FROM Products;
$result = mysql_query($query, $con);
mysql_close($con);
?>
Inserting data:
Example:
<?php
$con = mysql_connect(localhost, john, smith);
mysql_select_db(MyDB, $con);
$query = INSERT INTO Names VALUES(John, Smith);
if(mysql_query($query, $con)) {
echo Record added;
}
else {
echo Something went wrong;
}
mysql_close($con);
?>
Retrieving data:
Data is retrieved using the SELECT statement, the statement returns data rows.
To get the number of the retrieved rows, use the function mysql_num_rows().
mysql_num_rows() takes one argument, which is the query result index.
mysql_num_rows() returns an integer, which is the number of retrieved rows.
Example:
<?php
$con = mysql_connect(localhost, john, smith);
mysql_select_db(MyDB, $con);
$query = SELECT * FROM Products;
$result = mysql_query($query, $con);
$num = $mysql_num_rows($result);
echo The number of rows = $num;
mysql_close($con);
?>
You can use the number of rows to make a loop and display all the result rows.
But a better solution is to make a while loop using the function mysql_fetch_array().
mysql_fetch_array() takes one argument, which is the result index.
mysql_fetch_array() returns an array of the next fetched row, or false if no more rows.

Example:
<?php
$con = mysql_connect(localhost, john, smith);
mysql_select_db(MyDB, $con);
$query = SELECT first_name, last_name FROM Products;
$result = mysql_query($query, $con);
while($dataArray = mysql_fetch_array($result) {
$firstName = $dataArray[first_name];
$lastName = $dataArray[last_name];
echo $firstName $lastName<br />\n;
}
mysql_close($con);
?>

You might also like