The document provides an introduction to PHP, highlighting its use as a server-side scripting language similar to JSP and ASP for generating HTML pages. It covers fundamental PHP concepts such as variables, strings, functions, arrays, and SQL syntax for database interaction, along with examples of each. Additionally, it discusses connecting to a MySQL database, executing SQL statements, and handling data retrieval effectively.
PHP Introduction PHPserves the same purpose as Java Server Pages (JSP) and Active Server Pages (ASP) All are server-side languages “parsed” by a web server Script execution results are sent to a browser as an HTML page PHP is a type-less language
3.
PHP Structure Tradition:Start with an HTML file Add special tags to separate PHP code from HTML statements Web server parses the PHP file, producing HTML Now can be used to output XML, image, PDF, just by setting content-type
4.
Example: myfirst.php <html><body> <?php //A comment /*Or comment like this*/ print("<b>Hello world</b>"); $v = 5; print("<p>Hello again " . $v ); print("<p>Hello a third time $v"); ?> </body> </html>
5.
Variables All variablesstart with a dollar sign, $ $u = 5; $v = “hello”; $w = 1.22; $x = $u + $v; //arithmetic with + - ONLY $y = $v . $v; //concatenation with period operator $x = $u . $u; //produces 55, not 10
String-Related Functions $v= “hello”; strlen( $v); //returns 5 trim( $v); //trims any spaces on either side of a string $x = strtolower ($v); //$x has hello $x = strtoupper($v); //$x has HELLO $str = “abcdef”; $a = substr( $str, 3, 3 ); # of characters to copy Start position, zero indexed Source string “ def” Can be negative to start from right side
8.
Getting HTML FormData There are 3 ways to get form data in PHP Global variables – this is a bad way because of security problems. PHP creates a variable with a name matching the form field name in the source HTML. POST variable associative array Prior to version 4.1, $HTTP_POST_VARS 4.1 and after, $_POST GET variable associative array Same as POST, but use GET
9.
Examples Global variables (HTML has field with name ‘abc’) print ($abc); POST print($_POST(‘abc’)); //4.1 and after GET print($_GET(‘abc’)); //4.1 and after
10.
Comparing Strings strcmp($a, $b ); //works like C function Returns: – 1 if first string less than second string 0 if the same 1 if first string greater than second string It is case sensitive
11.
PHP Syntax SimilaritiesHas a switch statement for loop is the same, but uses PHP variable syntax for ($i=0; $i < 10; $i++ ){ …. } while and if are also what you’d expect Standard logical operators: ==, &&, <, > …
12.
Other Useful Functionsround ($a); //rounds a number is_numeric($v); //returns true/false rand($start, $end); //Produces int rand
13.
Current Date/Time Usedate function to get the current date. Takes a format string to provide the date in a format you want. See http://php.net/date . Use time function to get the current time. Returns the current time measured in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT).
External PHP FilesCan use require or include Require will produce a fatal error if the file cannot be found Include will just ignore a missing script file require(‘my.php’); include(‘my.php’); The files can contain PHP and/or HTML
Iterating Over Arraysfor ($i=0; $i<count($a); $i++ ) { print ($a[i]); } foreach( $a as $item ) { print( “<p>$item”); } Array variable Local variable. Set to next array element each iteration.
18.
Other Array Functions$m = max($a); //returns max value in array $m = min($a); //returns min value in array $s = array_sum($a); //returns sum or array values sort($a); //sorts the items in the array. Changes //the array itself Optional second argument is “sort flags” to control the sort.
19.
Associative Arrays Arrayscontaining key/value pairs $s = array( ‘a’=>’alpha’, ‘b’=>’beta’, … ); print ( $s[‘b’] ); The parameter to the left of => is the key. The right parameter is the value.
20.
SQL – StructuredQuery Language A language for accessing relational databases Relational databases have tables Tables have fields and contain rows of data
21.
SQL Syntax –SELECT Used for retrieving data from a database SELECT [fields] FROM [tables] WHERE [expr] Examples select * from users select abc, def from mytable where ghi=5
22.
SQL Syntax –INSERT Used to insert new data in a table INSERT INTO [table] [field names] VALUES [values] Examples insert into users (abc,def,ghi) values (‘111’,22,’cc) insert into xyz values (1,2,3,4,5)
23.
SQL Syntax –UPDATE Updating one or more values in existing rows in a table UPDATE [table] SET [name=value pairs] WHERE [expression] Examples update mytable set a=‘aaa’, b=55 where c=11
24.
PHP and MysqlDatabase 5 steps Connect to the Mysql DBMS Pick a database Execute an SQL statement If the SQL was a ‘select’, retrieve the data Close the connection
25.
Connecting to MysqlDBMS $con = mysql_connect( /* 3 arguments */ ); Your Mysql DBMS server process network location Your Mysql user ID Your Mysql user password For tonight only, mysql_connect(‘www.freesql.org’,’upeworkshop’,’upeworkshop’);
Executing an SQLStatement mysql_query( /*SQL statement*/ ); Proper form for any SQL not a Select if ( !mysql_query ( “update a ….” ); ) { echo mysql_error(); //for easy debugging, not for final user-oriented website } //returns true/false if it worked, or not
28.
For Select SQLStatements $r = mysql_query( ‘select * from abc’ ); while ( $row = mysql_fetch_row( $r ) ) { … } $row contains a row of data returns false when no more rows available Iterating through the fields in the row foreach ( $row as $item ) { … } OR access the fields using index position (zero indexed) OR put results in an associative array – less error prone while ($row = mysql_fetch_assoc($r)){ echo $row[‘firstname’]; }