LAMP = Linux, Apache, MySQL, PHP
Why PHP?
• Open Source = FREE.
• Available on practically any platform.
• Very ubiquitous. Most web hosting services offer...
PHP Syntax and Operators
• Started as a "template" language for dynamic webpages.Now
mostly used as a server-side scriptin...
Some PHP Operators
See Arithmetic Operators page
(http://www.php.net/manual/en/language.operators.arithmetic.php)
Assignme...
HTML Code: Nested Structures
// PHP is typically embedded in HTML code.
<html>
<body>
<table border>
<tr> <th>ID</th> <th>...
Simple PHP Example
• A PHP scripting block is delineated by:
<?php

start tag

?>

end tag

• A PHP scripting block
• can ...
Multiple Code Declaration Blocks
PHP code declaration blocks execute on Web server
first before Web page is sent to client...
Opening and Closing
MySQL Connection
/* The connection is stored in variable $DBConnect for later
use in the script */
<?p...
PHP and MySQL
• PRIMARY KEY clause indicates a field or fields that
will be used as a referential index for the table
• AU...
Adding, Deleting, Updating Records
// INSERT Example
// omit auto_increment field, put null to no data
field$SQLstring = "...
PHP and MySQL
• mysql_connect() function opens a connection to a MySQL
database server

• The mysql_close() function close...
Working with Query Results
• mysql_fetch_row() returns the fields in the current row of
a result set into an indexed array...
Function: mysql_affected_rows()
$SQLstring = "UPDATE student SET id = 33213
WHERE name='Zhang'";
$QueryResult = @mysql_que...
Indexed Arrays
Two ways to create indexed arrays (numeric keys).
1. Using the array() construct
$array_name = array(elemen...
Iterating through an Array
This declares and initializes an indexed array named
$DaysOfWeek[] and uses a foreach statement...
Retrieving Records
into an Indexed Array
mysql_fetch_row() returns the fields in the current row of
a result set into an i...
Retrieving Records
into an Indexed Array (contd)
$SQLstring = "SELECT * FROM student";
$QueryResult = @mysql_query($SQLstr...
Associative Arrays
Two ways to create associative arrays (keys are
alphanumeric names).
1. Using the array() construct
$ar...
Autoglobals
• Predefined global arrays which contain client, server, and
environment information that you can use in your ...
Data Validation
Use Web form controls for validating input types (such as check
boxes, radio buttons, and selection lists)...
Input Types
text

A single line text field

password

Same as text, but the input is not displayed

textarea

A multi-line...
Web Form Input Type="text"
<form action="display.php" method="get">
<label>name: </label>
<input type="text" name="name"/>...
<!DOCTYPE html>
<html>
<head> <title>arrays2.php</title> </head>
<body>
<?php
echo "Method1: Loop Through an Indexed Array...
<!DOCTYPE html>
<html>
<head>
<title>MySQL Database - create table</title>
</head>
<body>
<h1>Creating table customerconta...
webform1.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=UTF-8">
<title>GET...
Upcoming SlideShare
Loading in …5
×

Php summary

1,197
-1

Published on

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
1,197
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
9
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Php summary

  1. 1. LAMP = Linux, Apache, MySQL, PHP
  2. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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>
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×