SlideShare uma empresa Scribd logo
1 de 25
Baixar para ler offline
LAMP = Linux, Apache, MySQL, PHP
Why PHP?
• Open Source = FREE.
• Available on practically any platform.
• Very ubiquitous. Most web hosting services offer PHP.
(See LAMP software bundle on previous slide).
• Why some people hate it:

http://webonastick.com/php.html

• Why others are more upbeat:
http://net.tutsplus.com/articles/editorials/why-2013-is-the-year-of-php/

• Greatest Strength: Strong support for Open Database
Connectivity (ODBC). PHP can access and manipulate
any ODBC compliant database, including:
• MySQL, Oracle, MSSQLServer, MSAccess
• MongoDB, Cassandra
PHP Syntax and Operators
• Started as a "template" language for dynamic webpages.Now
mostly used as a server-side scripting language for web
development.
• Acts as a "filter":
• INPUT: text and/or PHP instructions from a file or data stream
• OUTPUT: another data stream (usually HTML, but can also be JSON or XML)

• Syntax is similar to C/C++/Java. OPERATORS:
•
•
•
•
•
•
•

Arithmetic
Comparison
Bitwise
Assignment
Execution
Array
Type

• Great reference material:
• http://www.php.net/
• http://www.w3schools.com/php/
Some PHP Operators
See Arithmetic Operators page
(http://www.php.net/manual/en/language.operators.arithmetic.php)
Assignment
Same as:
$a += $b
$a = $a + $b
Addition
$a -= $b
$a = $a - $b
Subtraction
$a *= $b
$a = $a * $b
Multiplication
$a /= $b
$a = $a / $b
Division
$a %= $b
$a = $a % $b
Modulus
See String Operators page
(http://www.php.net/manual/en/language.operators.string.php)
$a .= $b
$a = $a . $b
Concatenate
See Bitwise Operators page
(http://www.php.net/manual/en/language.operators.bitwise.php)
$a &= $b
$a = $a & $b
Bitwise And
$a |= $b
$a = $a | $b
Bitwise Or
$a ^= $b
$a = $a ^ $b
Bitwise Xor
$a <<= $b
$a = $a << $b
Left shift
$a >>= $b
$a = $a >> $b
Right shift
HTML Code: Nested Structures
// PHP is typically embedded in HTML code.
<html>
<body>
<table border>
<tr> <th>ID</th> <th>Name</th> <th>Department</th> </tr>
<tr> <td>00128</td> <td>Zhang</td> <td>Comp. Sci.</td> </tr>
</table>
<form action="PersonQuery" method=get> Search for:
<select name="persontype">
<option value="student" selected>Student </option>
<option value="instructor"> Instructor </option>
</select>
<br> Name: <input type=text size=20 name="name">
<input type=submit value="submit">
</form>
</body>
</html>
5
Simple PHP Example
• A PHP scripting block is delineated by:
<?php

start tag

?>

end tag

• A PHP scripting block
• can be placed anywhere in the HTML document.
• Each code line must end with a semicolon.

• Two ways to output text:
• echo and print.

• All variables in start with a $ symbol.
• Comments: // or /* */

6
Multiple Code Declaration Blocks
PHP code declaration blocks execute on Web server
first before Web page is sent to client.
...
</head>
<body>
<h1>Multiple Script Sections</h1>
<h2>First Script Section</h2>
<p> Output from the first script section.</p>
<h2>Second Script Section</h2>
<p> Output from the second script section.</p>
</body>
</html>
7
Opening and Closing
MySQL Connection
/* The connection is stored in variable $DBConnect for later
use in the script */
<?php
// Create connection
$DBConnect =
mysql_connect(“www.psme.foothill.edu”,“1234532","abc123","my_
db");
// Check connection
if (mysql_connect_errno($DBConnect))
{
echo "Failed to connect to MySQL: " .mysql_connect_error();
}
?>
8
PHP and MySQL
• PRIMARY KEY clause indicates a field or fields that
will be used as a referential index for the table
• AUTO_INCREMENT clause creates a field that is
automatically updated with the next sequential value
for that column.
• NOT NULL clause creates a field that must contain
data.
• Use with the mysql_query() function
• DROP TABLE statement to delete a table
• UPDATE statement to update records
• DELETE statement to delete records
Adding, Deleting, Updating Records
// INSERT Example
// omit auto_increment field, put null to no data
field$SQLstring = "INSERT INTO $TableName " .
"(name, email, phone) " .
"VALUES ('Name2', 'name2@gmail.com', NULL)";
$QueryResult = mysql_query($SQLstring, $DBConnect);
// UPDATE Example
$SQLstring = "UPDATE customer SET name = 'Name_a', phone =
'510-112-3523' WHERE cust_id = 88 ";
$QueryResult = mysql_query($SQLstring, $DBConnect);
// DELETE Example
$SQLstring = "DELETE FROM $TableName WHERE cust_id = 88";
$QueryResult = mysql_query($SQLstring, $DBConnect);
PHP and MySQL
• mysql_connect() function opens a connection to a MySQL
database server

• The mysql_close() function closes a database connection
• You use the mysql_create_db() function to create a new
database
• The mysql_select_db() function selects a database

• You use the mysql_drop_db() function to delete a database
• The mysql_query() function sends SQL statements to MySQL
• A result pointer is a special type of variable that refers
to the currently selected row in a resultset
• You use the CREATE TABLE statement with the mysql_query()
function to create a table
Working with Query Results
• mysql_fetch_row() returns the fields in the current row of
a result set into an indexed array and moves the result
pointer to the next row.
• mysql_fetch_assoc() returns the fields in the current row
of a resultset into an associative array and moves the
result pointer to the next row
• mysql_free_result() closes a resultset
• mysql_num_rows() returns the number of rows in a query
result, and the mysql_num_fields() function returns the
number of fields in a query result
• With queries that return results, such as SELECT
queries, you can use the mysql_num_rows() function to
find the number of records returned from the query
Function: mysql_affected_rows()
$SQLstring = "UPDATE student SET id = 33213
WHERE name='Zhang'";
$QueryResult = @mysql_query($SQLstring, $DBConnect);
if ($QueryResult === FALSE)
echo "<p>Unable to execute the query.</p>"
. "<p>Error code " . mysql_errno($DBConnect)
. ": " . mysql_error($DBConnect) . "</p>";
else
echo "<p>Successfully updated "
. mysql_affected_rows($DBConnect) . "
record(s).</p>";
Indexed Arrays
Two ways to create indexed arrays (numeric keys).
1. Using the array() construct
$array_name = array(element0, element1, element2,
element3);
2. Using square brackets[]. The next consecutive index
number is assigned automatically. Default start is 0.
$array_name[]
$array_name[]
$array_name[]
$array_name[]

=
=
=
=

element0;
element1;
element2;
element3;

Example: $array_name[100] = "array100";
Iterating through an Array
This declares and initializes an indexed array named
$DaysOfWeek[] and uses a foreach statement to iterate
through it:
$DaysOfWeek = array("Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday", "Saturday");
foreach ($DaysOfWeek as $Day) {
echo "<p>$Day</p>n";
}
Retrieving Records
into an Indexed Array
mysql_fetch_row() returns the fields in the current row of
a result set into an indexed array and moves the result
pointer to the next row
echo "<table width='100%‘ border='1'>";
echo "<tr><th>Make</th><th>Model</th>
<th>Price</th><th>Quantity</th></tr>";
$Row = mysql_fetch_row($QueryResult);
do {
echo "<tr><td>{$Row[0]}</td>";
echo "<td>{$Row[1]}</td>";
echo "<td align='right'>{$Row[2]}</td>";
echo "<td align='right'>{$Row[3]}</td></tr>";
$Row = mysql_fetch_row($QueryResult);
} while ($Row);
Retrieving Records
into an Indexed Array (contd)
$SQLstring = "SELECT * FROM student";
$QueryResult = @mysql_query($SQLstring, $DBConnect);

echo "<table width='100%' border='1'>n";
echo "<tr><th>ID</th><th>NAME</th><th>DEPT_NAME</th>
<th>tot_cred</th>tr>n";
while (($Row = mysql_fetch_row($QueryResult)) !== FALSE) {

echo "<tr><td>{$Row[0]}</td>";
echo "<td>{$Row[1]}</td>";
echo "<td>{$Row[2]}</td>";
echo "<td align='right'>{$Row[3]}</td> ></tr>n ";

}
echo "</table>n";
Associative Arrays
Two ways to create associative arrays (keys are
alphanumeric names).
1. Using the array() construct
$array_name = array(key => value, key2 => value2, …);
2. Using square brackets[].
$array_name["key3"] = "value3";
$array_name["key4"] = "value4";
Example:

echo "<p> The value of key3 is
{$array_name['key3']}.</p>n";
Autoglobals
• Predefined global arrays which contain client, server, and
environment information that you can use in your scripts.
• Autoglobals are associative arrays that can only be referenced
using an alphanumeric key, not an index number.
$_COOKIE - values passed to the current script as HTTP cookies
$_ENV - environment information
$_FILES - information about uploaded files
$_GET - values from a form submitted with the “get” method
$_POST - values from a form submitted with the “post” method
$_REQUEST -

all the elements in the $_COOKIE, $_GET, and $_POST arrays

$_SERVER - information about the Web server that served the current script
$_SESSION - session variables that are available to the current script
$GLOBALS - References to all variables defined with global scope
Data Validation
Use Web form controls for validating input types (such as check
boxes, radio buttons, and selection lists) that limit user from
entering invalid data.
Useful Functions:
• NUMERIC DATA: (is_double(), is_float(), is_int(), is_integer(),
is_long(), is_null(), is_numeric(), is_object(), is_real(),
is_string()).
• STRING DATA:
• stripslashes() removes the leading slashes for escape
sequences in strings.
• trim() removes any leading or trailing white space from a
string.
Input Types
text

A single line text field

password

Same as text, but the input is not displayed

textarea

A multi-line text field

radio

Set of radio buttons; user can select only 1.

checkbox

Set of checkboxes; user can select 0 or more.

option/select Drop-down lists

Button

Button

img

Button with an image

file

File upload button

hidden

Static value.

21
Web Form Input Type="text"
<form action="display.php" method="get">
<label>name: </label>
<input type="text" name="name"/><br />
<label>Address: </label>
<input type="text" Address=“Address"/><br />
<label>&nbsp;</label>
<input type="submit" value="Submit"/>
</form>
// Get data and store into variables:
$name = $_GET['name'];
$Address = $_GET[‘Address'];

22
<!DOCTYPE html>
<html>
<head> <title>arrays2.php</title> </head>
<body>
<?php
echo "Method1: Loop Through an Indexed Array
<br>";
$DaysOfWeek = array("Sunday", "Monday",
"Tuesday", "Wednesday", "Thursday", "Friday",
"Saturday");
foreach ($DaysOfWeek as $Day)
echo "$Day<br>";
echo "<br>Method2: Loop Through an Indexed
Array <br>";
$arrlength = count($DaysOfWeek);
for ($x = 0; $x < $arrlength; $x++) {
echo $DaysOfWeek[$x];
echo "<br>";
}
// Associative Array
$keys = array("key1" => "value1",
"value2", "kay3" => "value3");
echo "Loop Through an Associative
echo "<br>";
foreach ($keys as $x => $x_value)
echo "Key=" . $x . ", Value="
echo "<br>";
}
?>
</body>
</html>

"key2" =>
Array";
{
. $x_value;

OUTPUT:
Method1: Loop Through an Indexed Array
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Method2: Loop Through an Indexed Array
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Loop Through an Associative Array
Key=key1, Value=value1
Key=key2, Value=value2
Key=kay3, Value=value3
<!DOCTYPE html>
<html>
<head>
<title>MySQL Database - create table</title>
</head>
<body>
<h1>Creating table customercontact with test</h1>
<?php
$host="www.psme.foothill.edu";
$user = "10062690";
$password = "glennb00";
$DBName = "test";

OUTPUT:

$DBConnect = mysql_connect($host, $user, $password) or die(mysql_error());
if ($DBConnect === FALSE) {
echo "<p>The Database server is not available.</p>";
die("<p>MySQL_error: " . mysql_error() . "<br />MySQL_errno: " . mysql_errno() . "</p>");
}
else {
echo "<p>The Database server is running.</p>";
$DBSelect = mysql_select_db($DBName, $DBConnect);
if ($DBSelect === FALSE) {
echo "<p>Could not Select the "$DBName" database: "
. "<br />MySQL_error: " . mysql_error($DBConnect) . "<br />MySQL_errno: " .
mysql_errno($DBConnect) . "</p>";
} else {
echo "<p>Database $DBName successfully selected</p>";
$TableName = "customercontact";
$SQLstring = "SHOW TABLES LIKE '$TableName'";
$Result = mysql_query($SQLstring, $DBConnect);
if (mysql_num_rows($Result) > 0) {
echo "<p>The $TableName table already exists!</p>";
} else {
$SQLstring = "CREATE TABLE customercontact (cust_id INT NOT NULL PRIMARY KEY, "
. "fname varchar(20), lname varchar(20), email varchar(20), phone
varchar(20))";
$Result = mysql_query($SQLstring, $DBConnect);
if ($Result === FALSE) {
echo "<p>Unable to execute the query. "
. "<br />MySQL_error: " . mysql_error($DBConnect)
. "<br />MySQL_errno: " .
mysql_errno($DBConnect) . "</p>";
}
else {
echo "<p>Successfully created the table. </p>";
}}}}
mysql_close($DBConnect);

?>
</body>
</html>

•

Creating table
customerconta
ct with test

•

The Database
server is
running.

•

Database test
successfully
selected

•

The
customercontac
t table already
exists!
webform1.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=UTF-8">
<title>GET</title>
</head>

<body>
<h1>Web Form - Method get</h1>
<h2 style="text-align: center">Form</h2>
<form name="scholarship" id="scholarship"
action="demo1.php" method="get">
<p>First Name: <input type="text"
name="fName" id="fName" /></p>
<p>Last Name: <input type="text"
name="lName" id="lName" /></p>
<p><input type="reset" value="Clear
Form" />&nbsp;&nbsp;<input type="submit"
name="Submit" id="Submit" value="Send Form"
/>
</form>
</body>
</html>

demo1.php
<!DOCTYPE html>
<html>
<head>
<title>demo1.php- GET</title>
</head>
<body>
<?php
$firstName = $_GET["fName"];
$lastName = $_GET["lName"];
echo "<p>Thank you for filling out the scholarship form, $firstName
$lastName.</p>";
echo '<table border="1">';
foreach ($_GET as $k => $v) {
echo '<tr><td>' . $k . '</td><td>' . $v . '</td></tr>'; }
echo '</table>';
echo "<p>$_GET<br />";
foreach ($_GET as $ArrayIndex => $ArrayValue) {
echo "ArrayIndex: {$ArrayIndex}; ArrayValue: {$ArrayValue}. <br />";
}
echo "</p>";
?>
</body>
</html>

Mais conteúdo relacionado

Mais procurados

Slick: Bringing Scala’s Powerful Features to Your Database Access
Slick: Bringing Scala’s Powerful Features to Your Database Access Slick: Bringing Scala’s Powerful Features to Your Database Access
Slick: Bringing Scala’s Powerful Features to Your Database Access Rebecca Grenier
 
PHP and MySQL PHP Written as a set of CGI binaries in C in ...
PHP and MySQL PHP Written as a set of CGI binaries in C in ...PHP and MySQL PHP Written as a set of CGI binaries in C in ...
PHP and MySQL PHP Written as a set of CGI binaries in C in ...webhostingguy
 
Brief introduction of Slick
Brief introduction of SlickBrief introduction of Slick
Brief introduction of SlickKnoldus Inc.
 
Php MySql For Beginners
Php MySql For BeginnersPhp MySql For Beginners
Php MySql For BeginnersPriti Solanki
 
Web2py Code Lab
Web2py Code LabWeb2py Code Lab
Web2py Code LabColin Su
 
Web2py tutorial to create db driven application.
Web2py tutorial to create db driven application.Web2py tutorial to create db driven application.
Web2py tutorial to create db driven application.fRui Apps
 
All Things Open 2016 -- Database Programming for Newbies
All Things Open 2016 -- Database Programming for NewbiesAll Things Open 2016 -- Database Programming for Newbies
All Things Open 2016 -- Database Programming for NewbiesDave Stokes
 
Learn PHP Lacture2
Learn PHP Lacture2Learn PHP Lacture2
Learn PHP Lacture2ADARSH BHATT
 
ZendCon2010 The Doctrine Project
ZendCon2010 The Doctrine ProjectZendCon2010 The Doctrine Project
ZendCon2010 The Doctrine ProjectJonathan Wage
 
Introduzione JQuery
Introduzione JQueryIntroduzione JQuery
Introduzione JQueryorestJump
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />tutorialsruby
 
Future of HTTP in CakePHP
Future of HTTP in CakePHPFuture of HTTP in CakePHP
Future of HTTP in CakePHPmarkstory
 
New in cakephp3
New in cakephp3New in cakephp3
New in cakephp3markstory
 

Mais procurados (19)

Mysql & Php
Mysql & PhpMysql & Php
Mysql & Php
 
Slick: Bringing Scala’s Powerful Features to Your Database Access
Slick: Bringing Scala’s Powerful Features to Your Database Access Slick: Bringing Scala’s Powerful Features to Your Database Access
Slick: Bringing Scala’s Powerful Features to Your Database Access
 
PHP and MySQL PHP Written as a set of CGI binaries in C in ...
PHP and MySQL PHP Written as a set of CGI binaries in C in ...PHP and MySQL PHP Written as a set of CGI binaries in C in ...
PHP and MySQL PHP Written as a set of CGI binaries in C in ...
 
Brief introduction of Slick
Brief introduction of SlickBrief introduction of Slick
Brief introduction of Slick
 
Php MySql For Beginners
Php MySql For BeginnersPhp MySql For Beginners
Php MySql For Beginners
 
Web2py Code Lab
Web2py Code LabWeb2py Code Lab
Web2py Code Lab
 
Advanced Querying with CakePHP 3
Advanced Querying with CakePHP 3Advanced Querying with CakePHP 3
Advanced Querying with CakePHP 3
 
Web2py tutorial to create db driven application.
Web2py tutorial to create db driven application.Web2py tutorial to create db driven application.
Web2py tutorial to create db driven application.
 
All Things Open 2016 -- Database Programming for Newbies
All Things Open 2016 -- Database Programming for NewbiesAll Things Open 2016 -- Database Programming for Newbies
All Things Open 2016 -- Database Programming for Newbies
 
Learn PHP Lacture2
Learn PHP Lacture2Learn PHP Lacture2
Learn PHP Lacture2
 
ZendCon2010 The Doctrine Project
ZendCon2010 The Doctrine ProjectZendCon2010 The Doctrine Project
ZendCon2010 The Doctrine Project
 
Drupal Render API
Drupal Render APIDrupal Render API
Drupal Render API
 
Advanced Django
Advanced DjangoAdvanced Django
Advanced Django
 
Introduzione JQuery
Introduzione JQueryIntroduzione JQuery
Introduzione JQuery
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
Future of HTTP in CakePHP
Future of HTTP in CakePHPFuture of HTTP in CakePHP
Future of HTTP in CakePHP
 
New in cakephp3
New in cakephp3New in cakephp3
New in cakephp3
 
phptut4
phptut4phptut4
phptut4
 
php part 2
php part 2php part 2
php part 2
 

Destaque

Social media marketing strategy for linkedin
Social media marketing strategy for linkedinSocial media marketing strategy for linkedin
Social media marketing strategy for linkedinSourabh Rana
 
2 инкубатор волонтерских проектов приложения
2 инкубатор волонтерских проектов приложения2 инкубатор волонтерских проектов приложения
2 инкубатор волонтерских проектов приложенияallapolishchuk
 
Active social media and generation gaps
Active social media and generation gapsActive social media and generation gaps
Active social media and generation gapsACTIVE-project
 
Tennis 2013 donetsk
Tennis 2013 donetskTennis 2013 donetsk
Tennis 2013 donetskAna Mirica
 
Dc feb 2013 l.falsafi
Dc feb 2013 l.falsafiDc feb 2013 l.falsafi
Dc feb 2013 l.falsafileilifalsafi
 
Apresentação prof luíz senna
Apresentação prof luíz sennaApresentação prof luíz senna
Apresentação prof luíz sennaDyone Andrade
 
17ª SECOM CALCOMUNIC - Proposta Comercial
17ª SECOM CALCOMUNIC - Proposta Comercial17ª SECOM CALCOMUNIC - Proposta Comercial
17ª SECOM CALCOMUNIC - Proposta ComercialAndré Aga Rizzo
 
Козырная карта
Козырная картаКозырная карта
Козырная картаcrazytheman
 
Barcelona Hospital de Sant Pau i de la Santa Creu
Barcelona Hospital de Sant Pau i de la Santa CreuBarcelona Hospital de Sant Pau i de la Santa Creu
Barcelona Hospital de Sant Pau i de la Santa CreuCarlos Colomer
 
Scorion dashboard 4 voorbeelden
Scorion dashboard 4 voorbeeldenScorion dashboard 4 voorbeelden
Scorion dashboard 4 voorbeeldenparantion
 
Moving the Goalposts: Why Museums Need to Play More - MuseumNext2012 - Ben Te...
Moving the Goalposts: Why Museums Need to Play More - MuseumNext2012 - Ben Te...Moving the Goalposts: Why Museums Need to Play More - MuseumNext2012 - Ben Te...
Moving the Goalposts: Why Museums Need to Play More - MuseumNext2012 - Ben Te...thoughtden
 

Destaque (20)

Social media marketing strategy for linkedin
Social media marketing strategy for linkedinSocial media marketing strategy for linkedin
Social media marketing strategy for linkedin
 
2 инкубатор волонтерских проектов приложения
2 инкубатор волонтерских проектов приложения2 инкубатор волонтерских проектов приложения
2 инкубатор волонтерских проектов приложения
 
Active social media and generation gaps
Active social media and generation gapsActive social media and generation gaps
Active social media and generation gaps
 
Folhetoeq1
Folhetoeq1Folhetoeq1
Folhetoeq1
 
Tennis 2013 donetsk
Tennis 2013 donetskTennis 2013 donetsk
Tennis 2013 donetsk
 
Dc feb 2013 l.falsafi
Dc feb 2013 l.falsafiDc feb 2013 l.falsafi
Dc feb 2013 l.falsafi
 
New York city
New York cityNew York city
New York city
 
1Q13 ISG Outsourcing Index, EMEA
1Q13 ISG Outsourcing Index, EMEA1Q13 ISG Outsourcing Index, EMEA
1Q13 ISG Outsourcing Index, EMEA
 
Apresentação prof luíz senna
Apresentação prof luíz sennaApresentação prof luíz senna
Apresentação prof luíz senna
 
17ª SECOM CALCOMUNIC - Proposta Comercial
17ª SECOM CALCOMUNIC - Proposta Comercial17ª SECOM CALCOMUNIC - Proposta Comercial
17ª SECOM CALCOMUNIC - Proposta Comercial
 
Козырная карта
Козырная картаКозырная карта
Козырная карта
 
Pp 5
Pp 5Pp 5
Pp 5
 
Guia 2
Guia 2Guia 2
Guia 2
 
Barcelona Hospital de Sant Pau i de la Santa Creu
Barcelona Hospital de Sant Pau i de la Santa CreuBarcelona Hospital de Sant Pau i de la Santa Creu
Barcelona Hospital de Sant Pau i de la Santa Creu
 
Scorion dashboard 4 voorbeelden
Scorion dashboard 4 voorbeeldenScorion dashboard 4 voorbeelden
Scorion dashboard 4 voorbeelden
 
Final pink panthers_03_30
Final pink panthers_03_30Final pink panthers_03_30
Final pink panthers_03_30
 
Smau bologna2012
Smau bologna2012Smau bologna2012
Smau bologna2012
 
Collection highlights
Collection highlightsCollection highlights
Collection highlights
 
The Future of Effective Governance
The Future of Effective GovernanceThe Future of Effective Governance
The Future of Effective Governance
 
Moving the Goalposts: Why Museums Need to Play More - MuseumNext2012 - Ben Te...
Moving the Goalposts: Why Museums Need to Play More - MuseumNext2012 - Ben Te...Moving the Goalposts: Why Museums Need to Play More - MuseumNext2012 - Ben Te...
Moving the Goalposts: Why Museums Need to Play More - MuseumNext2012 - Ben Te...
 

Semelhante a Php summary

PHP - Getting good with MySQL part II
 PHP - Getting good with MySQL part II PHP - Getting good with MySQL part II
PHP - Getting good with MySQL part IIFirdaus Adib
 
Web Technologies - forms and actions
Web Technologies -  forms and actionsWeb Technologies -  forms and actions
Web Technologies - forms and actionsAren Zomorodian
 
Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010Michelangelo van Dam
 
PHP and Rich Internet Applications
PHP and Rich Internet ApplicationsPHP and Rich Internet Applications
PHP and Rich Internet Applicationselliando dias
 
PHP and MySQL.pptx
PHP and MySQL.pptxPHP and MySQL.pptx
PHP and MySQL.pptxnatesanp1234
 
Php classes in mumbai
Php classes in mumbaiPhp classes in mumbai
Php classes in mumbaiaadi Surve
 
Mojo – Simple REST Server
Mojo – Simple REST ServerMojo – Simple REST Server
Mojo – Simple REST Serverhendrikvb
 
Intro to php
Intro to phpIntro to php
Intro to phpSp Singh
 
Service discovery and configuration provisioning
Service discovery and configuration provisioningService discovery and configuration provisioning
Service discovery and configuration provisioningSource Ministry
 
Scaling php applications with redis
Scaling php applications with redisScaling php applications with redis
Scaling php applications with redisjimbojsb
 
Local data storage for mobile apps
Local data storage for mobile appsLocal data storage for mobile apps
Local data storage for mobile appsIvano Malavolta
 
Synapse india reviews on php and sql
Synapse india reviews on php and sqlSynapse india reviews on php and sql
Synapse india reviews on php and sqlsaritasingh19866
 
Supercharging WordPress Development - Wordcamp Brighton 2019
Supercharging WordPress Development - Wordcamp Brighton 2019Supercharging WordPress Development - Wordcamp Brighton 2019
Supercharging WordPress Development - Wordcamp Brighton 2019Adam Tomat
 
Exploring Symfony's Code
Exploring Symfony's CodeExploring Symfony's Code
Exploring Symfony's CodeWildan Maulana
 
How to Create Login and Registration API in PHP.pdf
How to Create Login and Registration API in PHP.pdfHow to Create Login and Registration API in PHP.pdf
How to Create Login and Registration API in PHP.pdfAppweb Coders
 
Local storage in Web apps
Local storage in Web appsLocal storage in Web apps
Local storage in Web appsIvano Malavolta
 

Semelhante a Php summary (20)

PHP - Getting good with MySQL part II
 PHP - Getting good with MySQL part II PHP - Getting good with MySQL part II
PHP - Getting good with MySQL part II
 
PHP with MySQL
PHP with MySQLPHP with MySQL
PHP with MySQL
 
Web Technologies - forms and actions
Web Technologies -  forms and actionsWeb Technologies -  forms and actions
Web Technologies - forms and actions
 
phptut4
phptut4phptut4
phptut4
 
Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010
 
PHP and Rich Internet Applications
PHP and Rich Internet ApplicationsPHP and Rich Internet Applications
PHP and Rich Internet Applications
 
PHP and MySQL.pptx
PHP and MySQL.pptxPHP and MySQL.pptx
PHP and MySQL.pptx
 
Php classes in mumbai
Php classes in mumbaiPhp classes in mumbai
Php classes in mumbai
 
Mojo – Simple REST Server
Mojo – Simple REST ServerMojo – Simple REST Server
Mojo – Simple REST Server
 
Php basics
Php basicsPhp basics
Php basics
 
Intro to php
Intro to phpIntro to php
Intro to php
 
Service discovery and configuration provisioning
Service discovery and configuration provisioningService discovery and configuration provisioning
Service discovery and configuration provisioning
 
Scaling php applications with redis
Scaling php applications with redisScaling php applications with redis
Scaling php applications with redis
 
Local data storage for mobile apps
Local data storage for mobile appsLocal data storage for mobile apps
Local data storage for mobile apps
 
Synapse india reviews on php and sql
Synapse india reviews on php and sqlSynapse india reviews on php and sql
Synapse india reviews on php and sql
 
Supercharging WordPress Development - Wordcamp Brighton 2019
Supercharging WordPress Development - Wordcamp Brighton 2019Supercharging WordPress Development - Wordcamp Brighton 2019
Supercharging WordPress Development - Wordcamp Brighton 2019
 
Exploring Symfony's Code
Exploring Symfony's CodeExploring Symfony's Code
Exploring Symfony's Code
 
How to Create Login and Registration API in PHP.pdf
How to Create Login and Registration API in PHP.pdfHow to Create Login and Registration API in PHP.pdf
How to Create Login and Registration API in PHP.pdf
 
Fatc
FatcFatc
Fatc
 
Local storage in Web apps
Local storage in Web appsLocal storage in Web apps
Local storage in Web apps
 

Mais de Michelle Darling

Mais de Michelle Darling (7)

Family pics2august014
Family pics2august014Family pics2august014
Family pics2august014
 
Final pink panthers_03_31
Final pink panthers_03_31Final pink panthers_03_31
Final pink panthers_03_31
 
Rsplit apply combine
Rsplit apply combineRsplit apply combine
Rsplit apply combine
 
College day pressie
College day pressieCollege day pressie
College day pressie
 
R learning by examples
R learning by examplesR learning by examples
R learning by examples
 
V3 gamingcasestudy
V3 gamingcasestudyV3 gamingcasestudy
V3 gamingcasestudy
 
Cassandra NoSQL Tutorial
Cassandra NoSQL TutorialCassandra NoSQL Tutorial
Cassandra NoSQL Tutorial
 

Php summary

  • 1. LAMP = Linux, Apache, MySQL, PHP
  • 2. Why PHP? • Open Source = FREE. • Available on practically any platform. • Very ubiquitous. Most web hosting services offer PHP. (See LAMP software bundle on previous slide). • Why some people hate it: http://webonastick.com/php.html • Why others are more upbeat: http://net.tutsplus.com/articles/editorials/why-2013-is-the-year-of-php/ • Greatest Strength: Strong support for Open Database Connectivity (ODBC). PHP can access and manipulate any ODBC compliant database, including: • MySQL, Oracle, MSSQLServer, MSAccess • MongoDB, Cassandra
  • 3. PHP Syntax and Operators • Started as a "template" language for dynamic webpages.Now mostly used as a server-side scripting language for web development. • Acts as a "filter": • INPUT: text and/or PHP instructions from a file or data stream • OUTPUT: another data stream (usually HTML, but can also be JSON or XML) • Syntax is similar to C/C++/Java. OPERATORS: • • • • • • • Arithmetic Comparison Bitwise Assignment Execution Array Type • Great reference material: • http://www.php.net/ • http://www.w3schools.com/php/
  • 4. Some PHP Operators See Arithmetic Operators page (http://www.php.net/manual/en/language.operators.arithmetic.php) Assignment Same as: $a += $b $a = $a + $b Addition $a -= $b $a = $a - $b Subtraction $a *= $b $a = $a * $b Multiplication $a /= $b $a = $a / $b Division $a %= $b $a = $a % $b Modulus See String Operators page (http://www.php.net/manual/en/language.operators.string.php) $a .= $b $a = $a . $b Concatenate See Bitwise Operators page (http://www.php.net/manual/en/language.operators.bitwise.php) $a &= $b $a = $a & $b Bitwise And $a |= $b $a = $a | $b Bitwise Or $a ^= $b $a = $a ^ $b Bitwise Xor $a <<= $b $a = $a << $b Left shift $a >>= $b $a = $a >> $b Right shift
  • 5. HTML Code: Nested Structures // PHP is typically embedded in HTML code. <html> <body> <table border> <tr> <th>ID</th> <th>Name</th> <th>Department</th> </tr> <tr> <td>00128</td> <td>Zhang</td> <td>Comp. Sci.</td> </tr> </table> <form action="PersonQuery" method=get> Search for: <select name="persontype"> <option value="student" selected>Student </option> <option value="instructor"> Instructor </option> </select> <br> Name: <input type=text size=20 name="name"> <input type=submit value="submit"> </form> </body> </html> 5
  • 6. Simple PHP Example • A PHP scripting block is delineated by: <?php start tag ?> end tag • A PHP scripting block • can be placed anywhere in the HTML document. • Each code line must end with a semicolon. • Two ways to output text: • echo and print. • All variables in start with a $ symbol. • Comments: // or /* */ 6
  • 7. Multiple Code Declaration Blocks PHP code declaration blocks execute on Web server first before Web page is sent to client. ... </head> <body> <h1>Multiple Script Sections</h1> <h2>First Script Section</h2> <p> Output from the first script section.</p> <h2>Second Script Section</h2> <p> Output from the second script section.</p> </body> </html> 7
  • 8. Opening and Closing MySQL Connection /* The connection is stored in variable $DBConnect for later use in the script */ <?php // Create connection $DBConnect = mysql_connect(“www.psme.foothill.edu”,“1234532","abc123","my_ db"); // Check connection if (mysql_connect_errno($DBConnect)) { echo "Failed to connect to MySQL: " .mysql_connect_error(); } ?> 8
  • 9. PHP and MySQL • PRIMARY KEY clause indicates a field or fields that will be used as a referential index for the table • AUTO_INCREMENT clause creates a field that is automatically updated with the next sequential value for that column. • NOT NULL clause creates a field that must contain data. • Use with the mysql_query() function • DROP TABLE statement to delete a table • UPDATE statement to update records • DELETE statement to delete records
  • 10. Adding, Deleting, Updating Records // INSERT Example // omit auto_increment field, put null to no data field$SQLstring = "INSERT INTO $TableName " . "(name, email, phone) " . "VALUES ('Name2', 'name2@gmail.com', NULL)"; $QueryResult = mysql_query($SQLstring, $DBConnect); // UPDATE Example $SQLstring = "UPDATE customer SET name = 'Name_a', phone = '510-112-3523' WHERE cust_id = 88 "; $QueryResult = mysql_query($SQLstring, $DBConnect); // DELETE Example $SQLstring = "DELETE FROM $TableName WHERE cust_id = 88"; $QueryResult = mysql_query($SQLstring, $DBConnect);
  • 11. PHP and MySQL • mysql_connect() function opens a connection to a MySQL database server • The mysql_close() function closes a database connection • You use the mysql_create_db() function to create a new database • The mysql_select_db() function selects a database • You use the mysql_drop_db() function to delete a database • The mysql_query() function sends SQL statements to MySQL • A result pointer is a special type of variable that refers to the currently selected row in a resultset • You use the CREATE TABLE statement with the mysql_query() function to create a table
  • 12. Working with Query Results • mysql_fetch_row() returns the fields in the current row of a result set into an indexed array and moves the result pointer to the next row. • mysql_fetch_assoc() returns the fields in the current row of a resultset into an associative array and moves the result pointer to the next row • mysql_free_result() closes a resultset • mysql_num_rows() returns the number of rows in a query result, and the mysql_num_fields() function returns the number of fields in a query result • With queries that return results, such as SELECT queries, you can use the mysql_num_rows() function to find the number of records returned from the query
  • 13. Function: mysql_affected_rows() $SQLstring = "UPDATE student SET id = 33213 WHERE name='Zhang'"; $QueryResult = @mysql_query($SQLstring, $DBConnect); if ($QueryResult === FALSE) echo "<p>Unable to execute the query.</p>" . "<p>Error code " . mysql_errno($DBConnect) . ": " . mysql_error($DBConnect) . "</p>"; else echo "<p>Successfully updated " . mysql_affected_rows($DBConnect) . " record(s).</p>";
  • 14. Indexed Arrays Two ways to create indexed arrays (numeric keys). 1. Using the array() construct $array_name = array(element0, element1, element2, element3); 2. Using square brackets[]. The next consecutive index number is assigned automatically. Default start is 0. $array_name[] $array_name[] $array_name[] $array_name[] = = = = element0; element1; element2; element3; Example: $array_name[100] = "array100";
  • 15. Iterating through an Array This declares and initializes an indexed array named $DaysOfWeek[] and uses a foreach statement to iterate through it: $DaysOfWeek = array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"); foreach ($DaysOfWeek as $Day) { echo "<p>$Day</p>n"; }
  • 16. Retrieving Records into an Indexed Array mysql_fetch_row() returns the fields in the current row of a result set into an indexed array and moves the result pointer to the next row echo "<table width='100%‘ border='1'>"; echo "<tr><th>Make</th><th>Model</th> <th>Price</th><th>Quantity</th></tr>"; $Row = mysql_fetch_row($QueryResult); do { echo "<tr><td>{$Row[0]}</td>"; echo "<td>{$Row[1]}</td>"; echo "<td align='right'>{$Row[2]}</td>"; echo "<td align='right'>{$Row[3]}</td></tr>"; $Row = mysql_fetch_row($QueryResult); } while ($Row);
  • 17. Retrieving Records into an Indexed Array (contd) $SQLstring = "SELECT * FROM student"; $QueryResult = @mysql_query($SQLstring, $DBConnect); echo "<table width='100%' border='1'>n"; echo "<tr><th>ID</th><th>NAME</th><th>DEPT_NAME</th> <th>tot_cred</th>tr>n"; while (($Row = mysql_fetch_row($QueryResult)) !== FALSE) { echo "<tr><td>{$Row[0]}</td>"; echo "<td>{$Row[1]}</td>"; echo "<td>{$Row[2]}</td>"; echo "<td align='right'>{$Row[3]}</td> ></tr>n "; } echo "</table>n";
  • 18. Associative Arrays Two ways to create associative arrays (keys are alphanumeric names). 1. Using the array() construct $array_name = array(key => value, key2 => value2, …); 2. Using square brackets[]. $array_name["key3"] = "value3"; $array_name["key4"] = "value4"; Example: echo "<p> The value of key3 is {$array_name['key3']}.</p>n";
  • 19. Autoglobals • Predefined global arrays which contain client, server, and environment information that you can use in your scripts. • Autoglobals are associative arrays that can only be referenced using an alphanumeric key, not an index number. $_COOKIE - values passed to the current script as HTTP cookies $_ENV - environment information $_FILES - information about uploaded files $_GET - values from a form submitted with the “get” method $_POST - values from a form submitted with the “post” method $_REQUEST - all the elements in the $_COOKIE, $_GET, and $_POST arrays $_SERVER - information about the Web server that served the current script $_SESSION - session variables that are available to the current script $GLOBALS - References to all variables defined with global scope
  • 20. Data Validation Use Web form controls for validating input types (such as check boxes, radio buttons, and selection lists) that limit user from entering invalid data. Useful Functions: • NUMERIC DATA: (is_double(), is_float(), is_int(), is_integer(), is_long(), is_null(), is_numeric(), is_object(), is_real(), is_string()). • STRING DATA: • stripslashes() removes the leading slashes for escape sequences in strings. • trim() removes any leading or trailing white space from a string.
  • 21. Input Types text A single line text field password Same as text, but the input is not displayed textarea A multi-line text field radio Set of radio buttons; user can select only 1. checkbox Set of checkboxes; user can select 0 or more. option/select Drop-down lists Button Button img Button with an image file File upload button hidden Static value. 21
  • 22. Web Form Input Type="text" <form action="display.php" method="get"> <label>name: </label> <input type="text" name="name"/><br /> <label>Address: </label> <input type="text" Address=“Address"/><br /> <label>&nbsp;</label> <input type="submit" value="Submit"/> </form> // Get data and store into variables: $name = $_GET['name']; $Address = $_GET[‘Address']; 22
  • 23. <!DOCTYPE html> <html> <head> <title>arrays2.php</title> </head> <body> <?php echo "Method1: Loop Through an Indexed Array <br>"; $DaysOfWeek = array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"); foreach ($DaysOfWeek as $Day) echo "$Day<br>"; echo "<br>Method2: Loop Through an Indexed Array <br>"; $arrlength = count($DaysOfWeek); for ($x = 0; $x < $arrlength; $x++) { echo $DaysOfWeek[$x]; echo "<br>"; } // Associative Array $keys = array("key1" => "value1", "value2", "kay3" => "value3"); echo "Loop Through an Associative echo "<br>"; foreach ($keys as $x => $x_value) echo "Key=" . $x . ", Value=" echo "<br>"; } ?> </body> </html> "key2" => Array"; { . $x_value; OUTPUT: Method1: Loop Through an Indexed Array Sunday Monday Tuesday Wednesday Thursday Friday Saturday Method2: Loop Through an Indexed Array Sunday Monday Tuesday Wednesday Thursday Friday Saturday Loop Through an Associative Array Key=key1, Value=value1 Key=key2, Value=value2 Key=kay3, Value=value3
  • 24. <!DOCTYPE html> <html> <head> <title>MySQL Database - create table</title> </head> <body> <h1>Creating table customercontact with test</h1> <?php $host="www.psme.foothill.edu"; $user = "10062690"; $password = "glennb00"; $DBName = "test"; OUTPUT: $DBConnect = mysql_connect($host, $user, $password) or die(mysql_error()); if ($DBConnect === FALSE) { echo "<p>The Database server is not available.</p>"; die("<p>MySQL_error: " . mysql_error() . "<br />MySQL_errno: " . mysql_errno() . "</p>"); } else { echo "<p>The Database server is running.</p>"; $DBSelect = mysql_select_db($DBName, $DBConnect); if ($DBSelect === FALSE) { echo "<p>Could not Select the "$DBName" database: " . "<br />MySQL_error: " . mysql_error($DBConnect) . "<br />MySQL_errno: " . mysql_errno($DBConnect) . "</p>"; } else { echo "<p>Database $DBName successfully selected</p>"; $TableName = "customercontact"; $SQLstring = "SHOW TABLES LIKE '$TableName'"; $Result = mysql_query($SQLstring, $DBConnect); if (mysql_num_rows($Result) > 0) { echo "<p>The $TableName table already exists!</p>"; } else { $SQLstring = "CREATE TABLE customercontact (cust_id INT NOT NULL PRIMARY KEY, " . "fname varchar(20), lname varchar(20), email varchar(20), phone varchar(20))"; $Result = mysql_query($SQLstring, $DBConnect); if ($Result === FALSE) { echo "<p>Unable to execute the query. " . "<br />MySQL_error: " . mysql_error($DBConnect) . "<br />MySQL_errno: " . mysql_errno($DBConnect) . "</p>"; } else { echo "<p>Successfully created the table. </p>"; }}}} mysql_close($DBConnect); ?> </body> </html> • Creating table customerconta ct with test • The Database server is running. • Database test successfully selected • The customercontac t table already exists!
  • 25. webform1.html <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>GET</title> </head> <body> <h1>Web Form - Method get</h1> <h2 style="text-align: center">Form</h2> <form name="scholarship" id="scholarship" action="demo1.php" method="get"> <p>First Name: <input type="text" name="fName" id="fName" /></p> <p>Last Name: <input type="text" name="lName" id="lName" /></p> <p><input type="reset" value="Clear Form" />&nbsp;&nbsp;<input type="submit" name="Submit" id="Submit" value="Send Form" /> </form> </body> </html> demo1.php <!DOCTYPE html> <html> <head> <title>demo1.php- GET</title> </head> <body> <?php $firstName = $_GET["fName"]; $lastName = $_GET["lName"]; echo "<p>Thank you for filling out the scholarship form, $firstName $lastName.</p>"; echo '<table border="1">'; foreach ($_GET as $k => $v) { echo '<tr><td>' . $k . '</td><td>' . $v . '</td></tr>'; } echo '</table>'; echo "<p>$_GET<br />"; foreach ($_GET as $ArrayIndex => $ArrayValue) { echo "ArrayIndex: {$ArrayIndex}; ArrayValue: {$ArrayValue}. <br />"; } echo "</p>"; ?> </body> </html>