Presentation is loading. Please wait.

Presentation is loading. Please wait.

+ Intro to PHP and SQL James Ohene-Djan. + What We’ll Cover Introduction to PHP Explain example code Introduction to Database Using PHP/MySQL for database.

Similar presentations


Presentation on theme: "+ Intro to PHP and SQL James Ohene-Djan. + What We’ll Cover Introduction to PHP Explain example code Introduction to Database Using PHP/MySQL for database."— Presentation transcript:

1 + Intro to PHP and SQL James Ohene-Djan

2 + What We’ll Cover Introduction to PHP Explain example code Introduction to Database Using PHP/MySQL for database access

3 + Intro to PHP

4 + What is PHP? PHP == ‘ Hypertext Preprocessor ’ Open-source, server-side scripting language Used to generate dynamic webpages PHP scripts reside between reserved PHP tags This allows the programmer to embed PHP scripts within HTML pages

5 + What is PHP (cont’d) Interpreted language, scripts are parsed at run- time rather than compiled beforehand Executed on the server-side Source-code not visible by client ‘ View Source ’ in browsers does not display the PHP code Various built-in functions allow for fast development Compatible with many popular databases

6 + What is PHP (cont’d) Conceived in 1994, now used on +10 million web sites. Outputs not only HTML but can output XML, images (JPG & PNG), PDF files and even Flash movies all generated on the fly. Can write these files to the file system. Supports a wide-range of databases PHP also has support for talking to other services using protocols such as LDAP, IMAP, SNMP, NNTP, POP3, HTTP.

7 + What does PHP code look like? Structurally similar to C/C++ but more like JSPs Supports procedural and object-oriented paradigm (to some degree) All PHP statements end with a semi-colon Each PHP script must be enclosed in the reserved PHP tag <?php … ?>

8 + Comments in PHP Standard C, C++, and shell comment symbols // C++ and Java-style comment # Shell-style comments /* C-style comments These can span multiple lines */

9 + Variables in PHP PHP variables must begin with a “ $ ” sign Case-sensitive ($Foo != $foo != $fOo) Global and locally-scoped variables Global variables can be used anywhere Local variables restricted to a function or class Certain variable names reserved by PHP Form variables ($_POST, $_GET) Server variables ($_SERVER) Etc.

10 + Variable usage <?php $foo = 25;// Numerical variable $bar = “Hello”;// String variable $foo = ($foo * 7);// Multiplies foo by 7 $bar = ($bar * 7);// Invalid expression ?>

11 + Echo The PHP command ‘ echo ’ is used to output the parameters passed to it The typical usage for this is to send data to the client ’ s web-browser Syntax void echo (string arg1 [, string argn...]) In practice, arguments are not passed in parentheses since echo is a language construct rather than an actual function

12 + Echo example Notice how echo ‘ 5x5=$foo ’ outputs $foo rather than replacing it with 25 Strings in single quotes ( ‘ ’ ) are not interpreted or evaluated by PHP This is true for both variables and character escape-sequences (such as “ \n ” or “ \\ ” ) <?php $foo = 25;// Numerical variable $bar = “Hello”;// String variable echo $bar;// Outputs Hello echo $foo,$bar;// Outputs 25Hello echo “5x5=”,$foo;// Outputs 5x5=25 echo “5x5=$foo”;// Outputs 5x5=25 echo ‘5x5=$foo’;// Outputs 5x5=$foo ?>

13 + Run hello.php Test PHP <?php echo"Hello There "; ?>

14 + Arithmetic Operations $a - $b // subtraction $a * $b// multiplication $a / $b// division $a += 5// $a = $a+5 Also works for *= and /= <?php $a=15; $b=30; $total=$a+$b; Print $total; Print “ $total ”; // total is 45 ?>

15 + Concatenation Use a period to join strings into one. <?php $string1=“Hello”; $string2=“PHP”; $string3=$string1. “ ”. $string2; Print $string3; ?> Hello PHP

16 + Escaping the Character If the string has a set of double quotation marks that must remain visible, use the \ [backslash] before the quotation marks to ignore and display them. <?php $heading=“\”Computer Science\””; Print $heading; ?> “Computer Science”

17 + icecream.php

18 + ices.php

19 + PHP Control Structures  Control Structures: Are the structures within a language that allow us to control the flow of execution through a program or script.  Grouped into conditional (branching) structures (e.g. if/else) and repetition structures (e.g. while loops).  Example if/else if/else statement: <?php $foo =4; if ($foo == 0) { echo 'The variable foo is equal to 0'; } else if (($foo > 0) && ($foo <= 5)) { echo 'The variable foo is between 1 and 5'; } else { echo 'The variable foo is equal to '.$foo; } ?>

20 + If... Else... If (condition) { Statements; } Else { Statement; } <?php $user = “John” If($user==“John”) { Print “Hello John.”; } Else { Print “You are not John.”; } ?> No THEN in PHP

21 + While Loops While (condition) { Statements; } <?php $count=0; While($count<3) { Print “hello PHP. ”; $count += 1; // $count = $count + 1; // or // $count++; ?> hello PHP. hello PHP. hello PHP.

22 + Date Display $datedisplay=date(“yyyy/m/d”); Print $datedisplay; # If the date is April 1 st, 2009 # It would display as 2009/4/1 <?php $datedisplay=date(“yyyy/m/d"); Print $datedisplay; ?> $datedisplay=date(“l, F m, Y”); Print $datedisplay; # If the date is April 1 st, 2009 # Wednesday, April 1, 2009 <?php $datedisplay=date("I/F m/ Y"); Print $datedisplay; ?>

23 Month, Day & Date Format Symbols MJan FJanuary m01 n1 Day of Monthd01 Day of MonthJ1 Day of WeeklMonday Day of WeekDMon

24 + Run Today.php Test Form PHP Today's date (according to this Web server) is <?php date_default_timezone_set('UTC'); echo date("l, F dS Y.");?>

25 + Functions Functions MUST be defined before then can be called Function headers are of the format Note that no return type is specified Unlike variables, function names are not case sensitive (foo( … ) == Foo( … ) == FoO( … )) function functionName($arg_1, $arg_2, …, $arg_n)

26 + Functions example <?php // This is a function function foo($arg_1, $arg_2) { $arg_2 = $arg_1 * $arg_2; return $arg_2; } $result_1 = foo(12, 3);// Store the function echo $result_1;// Outputs 36 echo foo(12, 3);// Outputs 36 ?>

27 + Include Files Include “opendb.php”; Include “closedb.php”; This inserts files; the code in files will be inserted into current code. This will provide useful and protective means once you connect to a database, as well as for other repeated functions. Include (“footer.php”); The file footer.php might look like: Copyright © 2008-2010 KSU ALL RIGHTS RESERVED URL: http://www.kent.edu

28 + PHP - Forms Access to the HTTP POST and GET data is simple in PHP The global variables $_POST[] and $_GET[] contain the request data <?php if ($_POST["submit"]) echo " You clicked Submit! "; else if ($_POST["cancel"]) echo " You clicked Cancel! "; ?>

29 + WHY PHP – Sessions ? Whenever you want to create a website that allows you to store and display information about a user, determine which user groups a person belongs to, utilize permissions on your website or you just want to do something cool on your site, PHP's Sessions are vital to each of these features. Cookies are about 30% unreliable right now and it's getting worse every day. More and more web browsers are starting to come with security and privacy settings and people browsing the net these days are starting to frown upon Cookies because they store information on their local computer that they do not want stored there. PHP has a great set of functions that can achieve the same results of Cookies and more without storing information on the user's computer. PHP Sessions store the information on the web server in a location that you chose in special files. These files are connected to the user's web browser via the server and a special ID called a "Session ID". This is nearly 99% flawless in operation and it is virtually invisible to the user.

30 + PHP - Sessions Sessions store their identifier in a cookie in the client’s browser Every page that uses session data must be proceeded by the session_start() function Session variables are then set and retrieved by accessing the global $_SESSION[] Save it as session.php <?php session_start(); if (!$_SESSION["count"]) $_SESSION["count"] = 0; if ($_GET["count"] == "yes") $_SESSION["count"] = $_SESSION["count"] + 1; echo " ".$_SESSION["count"]." "; ?> Click here to count

31 + Avoid Error PHP - Sessions PHP Example: "; session_start(); ?> Error! PHP Example: Correct Warning: Cannot send session cookie - headers already sent by (output started at session_header_error/session_error.php:2) in session_header_error/session_error.php on line 3 Warning: Cannot send session cache limiter - headers already sent (output started at session_header_error/session_error.php:2) in session_header_error/session_error.php on line 3

32 + Destroy PHP - Sessions Why it is necessary to destroy a session when the session will get destroyed when the user closes their browser. Imagine that you had a session registered called "access_granted" and you were using that to determine if the user was logged into your site based upon a username and password. Anytime you have a login feature, to make the users feel better, you should have a logout feature as well. That's where this cool function called session_destroy() comes in handy. session_destroy() will completely demolish your session (no, the computer won't blow up or self destruct) but it just deletes the session files and clears any trace of that session.session_destroy() Here's how we use session_destroy():session_destroy

33 + Destroy PHP - Sessions Step 5 - Destroy This Session "; if($_SESSION['name']){ echo "The session is still active"; } else { echo "Ok, the session is no longer active! "; echo " "; } ?>

34 + First PHP script Save as sample.php: Hello World! <?php echo “ Hello, World ” ; ?> <?php $myvar = "Hello World"; echo $myvar; ?>

35 + PHP References  http://www.php.net <-- php home page  http://www.phpbuilder.com/  http://www.devshed.com/  http://www.phpmyadmin.net/  http://www.hotscripts.com/PHP/  http://geocities.com/stuprojects/ChatroomDescription.htm  http://www.academic.marist.edu/~kbhkj/chatroom/chatroom.htm  http://www.aus-etrade.com/Scripts/php.php  http://www.codeproject.com/asp/CDIChatSubmit.asp  http://www.php.net/downloads <-- php download page  http://www.php.net/manual/en/install.windows.php <-- php installation manual  http://php.resourceindex.com/ <-- PHP resources like sample programs, text book references, etc.  http://www.daniweb.com/techtalkforums/forum17.html  php forums

36 + SQL Intro

37 + Relational Databases There are many different versions of Relational Database management systems available Oracle MySQL SQLite DB2 many others We’ll be using MySQL. The syntax of the Structured Query Language (SQL) is fairly standard.

38 + Databases _ creation CREATE TABLE tableName ( name VARCHAR(55), sex CHAR(1), age INT(3), birthdate DATE, salary DECIMAL(10,2), primary key(name) ); Types of attributes: char, varchar, int, smallint, decimal, date, float, etc. *varchar is a string with varying # of characters. In our example, 55 is the characters longest possible string allowed. *decimal(10,2) indicated 2 places after the decimal point and 10 total digits (including the decimal numbers)

39 + Databases _ creation 2 CREATE TABLE tableName ( name VARCHAR(55), sex CHAR(1) NOT NULL, age INT(3), birthdate DATE, salary DECIMAL(10,2) DEFAULT ‘0.00’, primary key(name) ); Primary key: primary key is a UNIQUE value. For every entry in your database this must be unique and not null and every DB must have one. NOT NULL: column must have a value DEFAULT: you can set a default value if no other value is inputted for that column.

40 + Databases _ indexed primary keys Instead of specifying a column as a primary key you can have the database create a column of numbers that will automatically increment with each entry inserted into the DB. Example: CREATE TABLE tableName ( id INT AUTO_INCREMENT, name VARCHAR(55), sex CHAR(1), age INT(3), birthdate DATE, salary DECIMAL(10,2), primary key(id) ); Entry 1 will have 1 as a key. Entry 2 will have 2 and so forth.

41 + Databases _ deletion DROP TABLE tableName;

42 + Databases _ insertion Inserting data in the database: INSERT INTO tableName(name,sex,age) VALUES(‘Mr. Freeze’,’M’,42); Also valid: INSERT INTO tableName(sex,name,age) VALUES(‘M’,’Mr. Freeze’,42); Order doesn’t matter.

43 + Databases _ querying data Always in the form of: SELECT …. FROM …. WHERE …. So select a column from your database. From a database Where x meets y condition.

44 + Databases _ updating Suppose we want to change Mr. Freeze’s age to 52. UPDATE tableName SET age = ’52’ WHERE name LIKE ‘Mr. Freeze’ And so forth.

45 + Databases _ aggregates This is the actual meat of using SQL. These are where you set your conditions, narrow down your table into a usable set. Here are the usable functions Group by Count Sum Avg Min/Max Order by

46 + Databases _ group by Group by lumps all the common attributes into one row. SELECT employee_id, MAX(salary) FROM Works_In GROUP BY dept_id; * MAX selects the maximum value in its () likewise for MIN

47 + Databases _ count Count counts the number of columns with the specified attribute. SELECT term, COUNT(course_id) FROM teaches GROUP BY term; We counted the number of courses taught during x term. AVG & SUM function pretty much the same way.

48 + Using a Database with PHP

49 + Functions Covered mysql_connect() mysql_select_db() include() mysql_query() mysql_num_rows() mysql_fetch_array() mysql_close()

50 + PHP _ connecting to the db This is the basic connect script for accessing your db: <?php mysql_connect(“localhost”,”username”,”password”) or die(mysql_error()); ?> Localhost indicates the current machine. So you’re asking the machine to connect to itself. The die(mysql_error) part says if there’s an error halt everything and display this error. If it errors on this part, it means either your host, username, or password are wrong.

51 + PHP _ error checking w/ echo Consider the connection script again with this modification: <?php mysql_connect(“localhost”,”username”,”password”) or die(mysql_error()); echo “Connected to MySQL.” ?> Later on you may be unable to differentiate where the error occurred. So while developing your code throw in some echo statements, they just print stuff to the screen. When PHP is done connecting to our database it tell us.

52 + PHP _ select the database. <?php mysql_connect(“localhost”,”username”,”password”) or die(mysql_error()); echo “Connected MySQL!”; mysql_select_db(“ljlayou_comp353” or die(mysql_error()); echo “Connected to database 353”; ?>

53 + PHP _ create/drop table <?php mysql_connect(“localhost”,”username”,”pw”) or die(mysql_error()); mysql_select_db(“ljlayou_comp353” or die(mysql_error()); mysql_query(“CREATE TABLE Works_In(…)“) or die(mysql_error()); ?> We’re querying PHP to tell MySQL to do something, in this case create the table. The same applies for dropping a table. As you can see our code is being reused over and over. It gets pretty repetitive like this. Again we tell php to stop everything if an error occurs.

54 + PHP _ insertion <?php mysql_connect(“localhost”,”username”,”pw”) or die(mysql_error()); mysql_select_db(“ljlayou_comp353” or die(mysql_error()); mysql_query(“INSERT INTO Works_In(company,position) VALUES(‘McDonalds’,’fry cook’)”); ?> We’re querying PHP to tell MySQL to do something, in this case insert a row into the table. As you can see our code is being reused over and over. It gets pretty repetitive like this.

55 + PHP _ selecting a table In order to manipulate, fetch, etc data from your database you must have PHP remember the result. So we store it in an array to preserve “columns”. PHP variables unlike Java do not need a type declaration <?php […] $result = mysql_query(“SELECT * FROM Works_In”) or die(mysql_error()); $row = mysql_fetch_array($result); echo “company: “.$row[‘company’]; echo “position:”.$row[‘position’]; ?> From these lines we see that each cell in the area is labeled under the column name. Using this method we can output or even compare data.

56 + PHP _ selecting a table <?php […] $result = mysql_query(“SELECT * FROM Works_In”) or die(mysql_error()); $row = mysql_fetch_array($result); echo “company: “.$row[‘company’]; echo “position:”.$row[‘position’]; ?> The ‘*’ symbol in the SELECT statement just means that we select all the columns in the table. The above statement however results in the first row only being shown.

57 + PHP _ selecting a table 2 To solve this problem, we loop continuously until there are no more rows to choose from. <?php […] while ($row = mysql_fetch_array($result)) { echo “company: “.$row[‘company’]. “ | “position:”.$row[‘position’]; echo “ ”;} ?> If you have noticed the ‘.’ symbol signifies a concatenation.

58 + PHP _ the formula We looked over it all. Here’s the general formula: <?php mysql_connect(“localhost”,”username”,”pw”) or die(mysql_error()); mysql_select_db(“databaseName” or die(mysql_error()); $result = mysql_query(yourQuery) or die(mysql_error()); $row = mysql_fetch_array($result); while ($row = mysql_fetch_array($result)) { … }; ?>

59 + Example – show data in the tables Function: list all tables in your database. Users can select one of tables, and show all contents in this table. second.php showtable.php

60 + selecttable.php MySQL Table Viewer <?php // change the value of $dbuser and $dbpass to your username and password $dbhost = 'hercules.cs.kent.edu:3306'; $dbuser = 'nruan'; $dbpass = ‘*****************’; $dbname = $dbuser; $table = 'account'; $conn = mysql_connect($dbhost, $dbuser, $dbpass); if (!$conn) { die('Could not connect: '. mysql_error()); } if (!mysql_select_db($dbname)) die("Can't select database");

61 + selecttable.php (cont.) $result = mysql_query("SHOW TABLES"); if (!$result) { die("Query to show fields from table failed"); } $num_row = mysql_num_rows($result); echo " Choose one table: "; echo " "; for($i=0; $i<$num_row; $i++) { $tablename=mysql_fetch_row($result); echo " {$tablename[0]} "; } echo " "; mysql_free_result($result); mysql_close($conn); ?>

62 + showtable.php MySQL Table Viewer <?php $dbhost = 'hercules.cs.kent.edu:3306'; $dbuser = 'nruan'; $dbpass = ‘**********’; $dbname = 'nruan'; $table = $_POST[“table”]; $conn = mysql_connect($dbhost, $dbuser, $dbpass); if (!$conn) die('Could not connect: '. mysql_error()); if (!mysql_select_db($dbname)) die("Can't select database"); $result = mysql_query("SELECT * FROM {$table}"); if (!$result) die("Query to show fields from table failed!". mysql_error());

63 + showtable.php (cont.) $fields_num = mysql_num_fields($result); echo " Table: {$table} "; echo " "; // printing table headers for($i=0; $i<$fields_num; $i++) { $field = mysql_fetch_field($result); echo " {$field->name} "; } echo " \n"; while($row = mysql_fetch_row($result)) { echo " "; // $row is array... foreach(.. ) puts every element // of $row to $cell variable foreach($row as $cell) echo " $cell "; echo " \n"; } mysql_free_result($result); mysql_close($conn); ?>


Download ppt "+ Intro to PHP and SQL James Ohene-Djan. + What We’ll Cover Introduction to PHP Explain example code Introduction to Database Using PHP/MySQL for database."

Similar presentations


Ads by Google