Sie sind auf Seite 1von 44

PHP & MYSQL

MARLON L. CASTRO
WHAT IS PHP
PHP stands for Hypertext Preprocessor

• 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
WHAT IS A PHP FILE?
• 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"

WHAT CAN PHP DO?


• PHP can generate dynamic page content
• PHP can create, open, read, write, delete, and close files on the server
• PHP can collect form data
• PHP can send and receive cookies
• PHP can add, delete, modify data in your database
• PHP can be used to control user-access
• PHP can encrypt data
• ***With PHP you are not limited to output HTML. You can output images, PDF files, and even Flash movies.
You can also output any text, such as XHTML and XML.***
BASIC PHP SYNTAX
• A PHP script can be placed anywhere in the document.
• A PHP script starts with <?php and ends with ?>
• The default file extension for PHP files is ".php".
• A PHP file normally contains HTML tags, and some PHP scripting code.

***Note: PHP statements end with a semicolon (;).***


HOW THE WEB SERVER PROCESSES PHP FILES
When a browser is pointed to a regular HTML file with an .html or .htm extension, the web server sends the
file, as is, to the browser. The browser processes the file and displays the web page described by the HTML tags
in the file. When a browser is pointed to a PHP file (with a .php extension), the web server looks for PHP
sections in the file and processes them or, more exactly, hands them to the PHP processor, instead of just
sending them as is to the browser. The web server/PHP processor processes the PHP file as follows:

1. The web server starts scanning the file in HTML mode. It assumes the statements are HTML and sends them
to the browser without any processing.

2. The web server continues in HTML mode until it encounters a PHP opening tag (<?php).

3. When it encounters a PHP opening tag, the web server hands the processing over to the PHP module. This
is sometimes called escaping from HTML. The web server then assumes that all statements are PHP
statements and uses the PHP module to execute the PHP statements. If there is output from PHP, the server
sends the output to the browser.

4. The web server continues in PHP mode until it encounters a PHP closing tag (?>).
5. When the web server encounters a PHP closing tag, it returns to HTML mode. It resumes scanning, and the
cycle continues from Step 1.
EXAMPLE
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>My First PHP Page</title>
</head>

<body>
<h1>My first PHP page</h1>
<?php
echo "Hello World";
?>
</body>
</html>

OUTPUT
My first PHP page
Hello World
COMMENTS IN PHP
• A comment in PHP code is a line that is not read/executed as part of the
program. Its only purpose is to be read by someone who is looking at the
code.
• Comments can be used to:
• Let others understand what you are doing
• Remind yourself of what you did - Most programmers have experienced
coming back to their own work a year or two later and having to re-figure
out what they did. Comments can remind you of what you were thinking
when you wrote the code
EXAMPLE OF COMMENTS IN PHP
<!DOCTYPE html>
<html>
<body>
<?php

// This is a single-line comment

# This is also a single-line comment

/*This is a multiple-lines comment block that spans over multiple lines */

// You can also use comments to leave out parts of a code line

$x = 5 /* + 15 */ + 5;
echo $x;
?>

</body>
</html>
PHP CASE SENSITIVITY

• In PHP, all keywords (e.g. if, else, while, echo, etc.), classes, functions, and
user-defined functions are NOT case-sensitive.

• However; all variable names are case-sensitive.


PHP VARIABLES
• In PHP, a variable starts with the $ sign, followed by the name of the variable.
• 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 ($age and $AGE are two different
variables)

***Remember that PHP variable names are case-sensitive!***


EXAMPLE OF DECLARING A VARIABLE
<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
?>

• After the execution of the statements above,


the variable $txt will hold the value Hello world!,
the variable $x will hold the value 5
the variable $y will hold the value 10.5

*** Note: When you assign a text value to a variable, put quotes around the value.
***
*** Note: Unlike other programming languages, PHP has no command for declaring
a variable. It is created the moment you first assign a value to it. ***
PHP DATA TYPES
PHP provides eight type of values, or data types.

Four are scalar (single value) types:


• Integers
• Floating-point numbers
• Strings
• Booleans

Two are compound (collection types)


• Arrays
• Objects

Two Special types


• Resource
• NULL
INTEGERS
• Integers are whole numbers, such as 1, 12, and 256. The range of acceptable values varies according to the
details of your platform but typically extends from -2,147,483,648 to -2,147,483,647.
• Integer literals can be written in decimal, octal, or hexadecimal. The sequence may begin with a plus (+) or
minus (-) sign. If there is no sign, positive is assumed
Example:
1998
-641
+33

FLOATING POINT NUMBERS


Floating point numbers represents numeric values with decimal digits sometimes called double. The range of
numbers is between 1.7E-308 and 1.7E-308.
Example.
3.14
0.017
-7.1
STRINGS
A string is a sequence of characters. String literals are delimited by either single of double quotes.
Example
‘Big Dog’
“Fat Hog”

BOOLEANS
A Boolean value represents a “Truth Value”. It says whether something is true or not.
example
$x=True
$y=false
ARRAYS
An array holds a group of values, which you can identify by position(a number, with zero being the first position) or some
identifying name(a string), called associative
example
$person[0]=“Marlon”;
$person[1]=“Lina”;
$person[2]=“Castro”;

$name[‘Firstname’]=“Marlon”;
$name[‘middlename’]=“Lina”;
$name[‘Lastname’]=“Castro”;

The array() construct creates and array


• Indexed Array
$person=array(‘Marlon’ , ’Lina’ , ‘Castro’)
• Associative Array
$name=array(‘Firstname’=>’Marlon’ , ‘Middlename’=>’Lina’ , ‘Lastname’=>’Castro’)

example
<?php
$person=array('Marlon','Lina','Castro');
echo $person[0];
?>
OBJECTS
PHP supports Object-Oriented Programming (OOP). OOP promotes clean modular design, simplifies debugging and
maintenance, and assists with code reuse.

Classes are the building blocks of objected oriented design. A class is a definition of a structure that contains
properties(functions). Classes are defined with the class keyword
Example

<?php
class Person{
public $name='';

function name($newname=NULL){
if(!is_null($newname)){
$this->name=$newname;
}
return $this->name;
}
}
$person=new Person;
$person->name="Marlon L. Castro";
echo "Hello ".$person->name();
?>
RESOURCES
A Resource is a special variable, holding a reference to an external resource. Resources are created and used by
special functions.

Example
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$db_selected = mysql_select_db('foo', $link);
$result = mysql_query('SELECT * WHERE 1=1');

NULL
There’s only one value of the NULL data type. That value is available through the case-insensitive keyword NULL.
The NULL value represents a variable that has no value

Example
$nothing=NULL;
PHP EXPRESSIONS AND OPERATORS
Operator Operation
new Create new object
! Logical Not
++ Increment

-- Decrement
* Multiplication
/ Division
% Modulus
+ Addition
- Subtraction
. String Concatenation
<, <= Less than, Less than or equal to
>, >= Greater than, Greater than or equal to
Operator Operation
== Value Equality
=== Type and Value Equality
!== Type and Value Inequality
&& Logical And
|| Logical Or
?: Conditional Operator
= Assignment
+=, -=,*=,/=,%= Assignment with operation
and Logical AND
or Logical OR
, List Separator
FLOW CONTROL STATEMENTS
• Conditional Statements, such as if/else and switch, allow a program to execute different pieces of code, or
none at all, depending on some condition.
• Loops, such as while and for, support the repeated execution of particular segment of code

IF STATEMENT
• The if statement checks the truthfulness of an expression and, if the expression is true, evaluates a
statement. An if statement looks like:
<?php
if(expression)
statement;
?>
• To specify an alternative statement to execute when the expression is false, use the else keyword
<?php
if(expression){
statement;
}else{
statement;
}
• To executes different codes for more than two conditions

if (expression) {
statement;
} elseif (expression) {
statement;
} else {
statement;
}
SWITCH STATEMENT
• A switch statement is given an expression and compares its value to all cases in the switch; all statements in a
matching case are executed, up to the first break keyword it finds. If none match, and a default is given, all
statements following the default keyword are executed

Example

switch(variable)
case(expression):
statement;
break;
case(expression):
statement;
break;
case(expression):
statement;
break;
default:
statement;
break;
WHILE LOOP
• The simplest form of loop
• If the expression evaluates to true, the statement is executed and then the expression is re-evaluated, if it
is still true, the body of the loop is executed again, and so on. The loop exits when the expression
evaluates to false.

example

<?php
$total=0;
$i=1;
while($i <=10){
$total+= $i;
$i++;
echo $total.", ";
}

Output:
1, 3, 6, 10, 15, 21, 28, 36, 45, 55,
?>
DO WHILE LOOP
Do-while loops are very similar to while loops, except the truth expression is checked at the end of each iteration
instead of in the beginning. The main difference from regular while loops is that the first iteration of a do-while
loop is guaranteed to run (the truth expression is only checked at the end of the iteration), whereas it may not
necessarily run with a regular while loop (the truth expression is checked at the beginning of each iteration, if it
evaluates to FALSE right from the beginning, the loop execution would end immediately).

Example

<?php
$i = 1;
do {
$i++;
echo $i.", ";
} while ($i < 5);
?>
Output:
2, 3, 4, 5,
FOR LOOP

The for loop statement is similar to the while statement, except it adds counter initialization and counter
manipulation expressions, and is often shorter and easier to read than the equivalent while loop.

Example

<?php
for($counter = 0; $counter < 10; $counter++){
echo "Counter is $counter\n,";
}
?>

Output:

Counter is 0 ,Counter is 1 ,Counter is 2 ,Counter is 3 ,Counter is 4 ,Counter is 5 ,Counter is 6 ,Counter is 7


,Counter is 8 ,Counter is 9
FOREACH STATEMENT
The foreach statement allows you to iterate over elements in an array.

Example

<?php
$name=array('Firstname'=>'Marlon','Middlename'=>'Lina','Lastname'=>'Castro');

foreach($name as $key=>$value){
echo "$value\n";
}
?>
SUPERGLOBALS
• Superglobals — Superglobals are built-in variables that are always available in all scopes
• Several predefined variables in PHP are "superglobals", which means they are available in all scopes throughout
a script. There is no need to do global $variable; to access them within functions or methods.

These superglobal variables are:


$GLOBALS
$_SERVER
$_GET
$_POST
$_FILES
$_COOKIE
$_SESSION
$_REQUEST
$_ENV
$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.

Example

<?php
$x = 75;
$y = 25;

function addition() {
$GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
}

addition();
echo $z;
?>
Output:
100
$_SERVER
$_SERVER is a PHP super global variable which holds information about headers, paths, and script locations.

Example

<?php
echo $_SERVER['PHP_SELF'];
echo "<br>";
echo $_SERVER['SERVER_NAME'];
echo "<br>";
echo $_SERVER['HTTP_HOST'];
echo "<br>";
echo $_SERVER['HTTP_USER_AGENT'];
echo "<br>";
echo $_SERVER['SCRIPT_NAME'];
?>

Output:
/test/index.php
localhost
localhost
Mozilla/5.0 (Windows NT 10.0; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0
/test/index.php
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)
Element/Code Description
$_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
Element/Code Description
$_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
someone@w3schools.com)
$_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
$_REQUEST
PHP $_REQUEST is used to collect data after submitting an HTML form.
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>
$_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.
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>
$_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.

Example
1st file
<html>
<body>
<a href="test_get.php?subject=PHP&web=W3schools.com">Test $GET</a>
</body>
</html>
Test_get.php
<html>
<body>
<?php
echo "Study " . $_GET['subject'] . " at " . $_GET['web'];
?>
</body>
</html>
WHAT IS MYSQL?
• MySQL is a database system used on the web
• MySQL is a database system that runs on a server
• MySQL is ideal for both small and large applications
• MySQL is very fast, reliable, and easy to use
• MySQL uses standard SQL
• MySQL compiles on a number of platforms
• MySQL is free to download and use
• MySQL is developed, distributed, and supported by Oracle Corporation
• MySQL is named after co-founder Monty Widenius's daughter: My
PHP DATA OBJECTS(PDO)
• PDO is a general database data access layer which uses a unified API (Application Programming Interface) with support for
MySQL among many other databases. It provides prepared statements, and significant flexibility in how data is returned.

• PDO - PHP Data Objects - is a database access layer providing a uniform method of access to multiple databases.

• It doesn't account for database-specific syntax, but can allow for the process of switching databases and platforms to be
fairly painless, simply by switching the connection string in many instances.

Database Support
The extension can support any database that a PDO driver has been written for. At the time of this writing, the following
database drivers are available:
• PDO_DBLIB ( FreeTDS / Microsoft SQL Server / Sybase )
• PDO_FIREBIRD ( Firebird/Interbase 6 )
• PDO_IBM ( IBM DB2 )
• PDO_INFORMIX ( IBM Informix Dynamic Server )
• PDO_MYSQL ( MySQL 3.x/4.x/5.x )
• PDO_OCI ( Oracle Call Interface )
• PDO_ODBC ( ODBC v3 (IBM DB2, unixODBC and win32 ODBC) )
• PDO_PGSQL ( PostgreSQL )
• PDO_SQLITE ( SQLite 3 and SQLite 2 )
• PDO_4D ( 4D )
CONNECTING
Different databases may have slightly different connection methods. Below, the method to connect to some of
the most popular databases are shown. You'll notice that the first three are identical, other then the database
type - and then SQLite has its own syntax.

try {
# MS SQL Server and Sybase with PDO_DBLIB
$DBH = new PDO("mssql:host=$host;dbname=$dbname, $user, $pass");
$DBH = new PDO("sybase:host=$host;dbname=$dbname, $user, $pass");

# MySQL with PDO_MYSQL


$DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);

# SQLite Database
$DBH = new PDO("sqlite:my/database/path/database.db");
}
catch(PDOException $e) {
echo $e->getMessage();
}
EXCEPTIONS AND PDO
PDO can use exceptions to handle errors, which means anything you do with PDO should be wrapped in a try/catch block. You
can force PDO into one of three error modes by setting the error mode attribute on your newly created database handle.
Here's the syntax:

1. $DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT );


2. $DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
3. $DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

No matter what error mode you set, an error connecting will always produce an exception, and creating a connection should
always be contained in a try/catch block.
PDO::ERRMODE_SILENT

This is the default error mode. If you leave it in this mode, you'll have to check for errors in the way you're probably used to if
you used the mysql or mysqli extensions. The other two methods are more ideal for DRY programming.
PDO::ERRMODE_WARNING

This mode will issue a standard PHP warning, and allow the program to continue execution. It's useful for debugging.
PDO::ERRMODE_EXCEPTION

This is the mode you should want in most situations. It fires an exception, allowing you to handle errors gracefully and hide
data that might help someone exploit your system.
INSERT AND UPDATE
Inserting new data, or updating existing data is one of the more common database operations. Using PDO, this
is normally a two-step process.

Example

Insert
$STH = $DBH->prepare("INSERT INTO folks ( first_name ) values ( 'Cathy' )");
$STH->execute();

Update
$STH = $DBH->prepare(“UPDATE folks SET first_name = 'Cathy' ");
$STH->execute();
SELECTING DATA
Data is obtained via the ->fetch(), a method of your statement handle. Before calling fetch, it's best to tell PDO
how you'd like the data to be fetched. You have the following options:
• PDO::FETCH_ASSOC: returns an array indexed by column name
• PDO::FETCH_BOTH (default): returns an array indexed by both column name and number
• PDO::FETCH_BOUND: Assigns the values of your columns to the variables set with the ->bindColumn()
method
• PDO::FETCH_CLASS: Assigns the values of your columns to properties of the named class. It will create the
properties if matching properties do not exist
• PDO::FETCH_INTO: Updates an existing instance of the named class
• PDO::FETCH_LAZY: Combines PDO::FETCH_BOTH/PDO::FETCH_OBJ, creating the object variable names as
they are used
• PDO::FETCH_NUM: returns an array indexed by column number
• PDO::FETCH_OBJ: returns an anonymous object with property names that correspond to the column
names
Example

FETCH_ASSOC
• This fetch type creates an associative array, indexed by column name. This should be quite familiar to anyone who has used the mysql/mysqli
extensions. Here's an example of selecting data with this method

$STH = $DBH->query('SELECT name, addr, city from folks');


$STH->setFetchMode(PDO::FETCH_ASSOC);
while($row = $STH->fetch()) {
echo $row['name'] . "\n";
echo $row['addr'] . "\n";
echo $row['city'] . "\n";
}

FETCH_OBJ
• This fetch type creates an object of std class for each row of fetched data. Here's an example:

$STH = $DBH->query('SELECT name, addr, city from folks');


$STH->setFetchMode(PDO::FETCH_OBJ);
while($row = $STH->fetch()) {
echo $row->name . "\n";
echo $row->addr . "\n";
echo $row->city . "\n";
}
DELETE
The ->exec() method is used for operations that can not return data other than the affected rows. The above
are two examples of using the exec method.

example
$DBH->exec('DELETE FROM folks WHERE 1');
REFERENCES
Rasmus Lerdorf, Kevin Tatroe & Peter MacIntyre(2006). Programming PHP. CA,USA: O’Reilly

https://www.w3schools.com/php/default.asp

https://code.tutsplus.com/tutorials/why-you-should-be-using-phps-pdo-for-database-access--net-12059

Das könnte Ihnen auch gefallen