php summary
DESCRIPTION
TRANSCRIPT
![Page 1: Php summary](https://reader034.vdocument.in/reader034/viewer/2022051816/5453e12ab1af9f84228b480e/html5/thumbnails/1.jpg)
LAMP = Linux, Apache, MySQL, PHP
![Page 2: Php summary](https://reader034.vdocument.in/reader034/viewer/2022051816/5453e12ab1af9f84228b480e/html5/thumbnails/2.jpg)
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
![Page 3: Php summary](https://reader034.vdocument.in/reader034/viewer/2022051816/5453e12ab1af9f84228b480e/html5/thumbnails/3.jpg)
PHP Syntax and Operators• Started as a "template" language for dynamic webpages.Nowmostly 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/
![Page 4: Php summary](https://reader034.vdocument.in/reader034/viewer/2022051816/5453e12ab1af9f84228b480e/html5/thumbnails/4.jpg)
Some PHP OperatorsSee 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
![Page 5: Php summary](https://reader034.vdocument.in/reader034/viewer/2022051816/5453e12ab1af9f84228b480e/html5/thumbnails/5.jpg)
HTML Code: Nested Structures
5
// 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>
![Page 6: Php summary](https://reader034.vdocument.in/reader034/viewer/2022051816/5453e12ab1af9f84228b480e/html5/thumbnails/6.jpg)
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
![Page 7: Php summary](https://reader034.vdocument.in/reader034/viewer/2022051816/5453e12ab1af9f84228b480e/html5/thumbnails/7.jpg)
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
![Page 8: Php summary](https://reader034.vdocument.in/reader034/viewer/2022051816/5453e12ab1af9f84228b480e/html5/thumbnails/8.jpg)
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 connectionif (mysql_connect_errno($DBConnect)){echo "Failed to connect to MySQL: " .mysql_connect_error();}
?>
8
![Page 9: Php summary](https://reader034.vdocument.in/reader034/viewer/2022051816/5453e12ab1af9f84228b480e/html5/thumbnails/9.jpg)
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
![Page 10: Php summary](https://reader034.vdocument.in/reader034/viewer/2022051816/5453e12ab1af9f84228b480e/html5/thumbnails/10.jpg)
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', '[email protected]', 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);
![Page 11: Php summary](https://reader034.vdocument.in/reader034/viewer/2022051816/5453e12ab1af9f84228b480e/html5/thumbnails/11.jpg)
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
![Page 12: Php summary](https://reader034.vdocument.in/reader034/viewer/2022051816/5453e12ab1af9f84228b480e/html5/thumbnails/12.jpg)
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
![Page 13: Php summary](https://reader034.vdocument.in/reader034/viewer/2022051816/5453e12ab1af9f84228b480e/html5/thumbnails/13.jpg)
Function: mysql_affected_rows()
$SQLstring = "UPDATE student SET id = 33213WHERE 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>";
![Page 14: Php summary](https://reader034.vdocument.in/reader034/viewer/2022051816/5453e12ab1af9f84228b480e/html5/thumbnails/14.jpg)
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[] = element0;
$array_name[] = element1;
$array_name[] = element2;
$array_name[] = element3;
Example: $array_name[100] = "array100";
![Page 15: Php summary](https://reader034.vdocument.in/reader034/viewer/2022051816/5453e12ab1af9f84228b480e/html5/thumbnails/15.jpg)
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";
}
![Page 16: Php summary](https://reader034.vdocument.in/reader034/viewer/2022051816/5453e12ab1af9f84228b480e/html5/thumbnails/16.jpg)
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);
![Page 17: Php summary](https://reader034.vdocument.in/reader034/viewer/2022051816/5453e12ab1af9f84228b480e/html5/thumbnails/17.jpg)
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";
![Page 18: Php summary](https://reader034.vdocument.in/reader034/viewer/2022051816/5453e12ab1af9f84228b480e/html5/thumbnails/18.jpg)
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";
![Page 19: Php summary](https://reader034.vdocument.in/reader034/viewer/2022051816/5453e12ab1af9f84228b480e/html5/thumbnails/19.jpg)
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
![Page 20: Php summary](https://reader034.vdocument.in/reader034/viewer/2022051816/5453e12ab1af9f84228b480e/html5/thumbnails/20.jpg)
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.
![Page 21: Php summary](https://reader034.vdocument.in/reader034/viewer/2022051816/5453e12ab1af9f84228b480e/html5/thumbnails/21.jpg)
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
![Page 22: Php summary](https://reader034.vdocument.in/reader034/viewer/2022051816/5453e12ab1af9f84228b480e/html5/thumbnails/22.jpg)
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> </label>
<input type="submit" value="Submit"/>
</form>
// Get data and store into variables:
$name = $_GET['name'];
$Address = $_GET[‘Address'];
22
![Page 23: Php summary](https://reader034.vdocument.in/reader034/viewer/2022051816/5453e12ab1af9f84228b480e/html5/thumbnails/23.jpg)
<!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", "key2" =>
"value2", "kay3" => "value3");
echo "Loop Through an Associative Array";
echo "<br>";
foreach ($keys as $x => $x_value) {
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>
</body>
</html>
OUTPUT:Method1: Loop Through an Indexed ArraySundayMondayTuesdayWednesdayThursdayFridaySaturday
Method2: Loop Through an Indexed ArraySundayMondayTuesdayWednesdayThursdayFridaySaturdayLoop Through an Associative ArrayKey=key1, Value=value1Key=key2, Value=value2Key=kay3, Value=value3
![Page 24: Php summary](https://reader034.vdocument.in/reader034/viewer/2022051816/5453e12ab1af9f84228b480e/html5/thumbnails/24.jpg)
<!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";
$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>
OUTPUT:
• Creating table customercontact with test
• The Database server is running.
• Database test successfully selected
• The customercontact table already exists!
![Page 25: Php summary](https://reader034.vdocument.in/reader034/viewer/2022051816/5453e12ab1af9f84228b480e/html5/thumbnails/25.jpg)
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" /> <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>