Upgrade to Pro — share decks privately, control downloads, hide ads and more …

PHP and Mysql

PHP and Mysql

PHP and Mysql Workshop at STI Taft, October 2008

Paul de Paula

October 01, 2008
Tweet

More Decks by Paul de Paula

Other Decks in Programming

Transcript

  1. PHP (recursive acronym for "PHP: Hypertext Preprocessor") is a widely-used

    Open Source general-purpose scripting language that is especially suited for Web development and can be embedded into HTML Start Up What is PHP
  2. There are three main areas where PHP scripts are used.

    1.  Server-side scripting 2.  Command line scripting 3.  Writing desktop applications Start Up Three major usage of PHP
  3. There are three main areas where PHP scripts are used.

    1.  Server-side scripting 2.  Command line scripting 3.  Writing desktop applications Start Up Three major usage of PHP
  4. Start Up Integer: An integer is a plain-vanilla whole number

    like 75, -95, 2000 or 1. <?php 
 
 $age = 99; 
 
 ?> Data Types in PHP
  5. Start Up Floating-point: A floating-point number is typically a fractional

    number such as 12.5 or 3.141592653589. Floating point numbers may be specified using either decimal or scientific notation. • <?php 
 
 $temperature = 56.89; 
 
 ?> Data Types in PHP
  6. Start Up String: A string is a sequence of characters,

    like "hello" or "abracadabra". String values may be enclosed in either double quotes ("") or single quotes(''). <?php 
 $identity = 'James Bond'; 
 $car = 'BMW'; 
 
 // this would contain the string "James Bond drives a BMW" 
 $sentence = "$identity drives a $car"; 
 echo $sentence; 
 ?> Data Types in PHP
  7. Start Up Stringing Things Along Why stop with numbers? PHP

    also allows you to add strings with the string concatenation operator, represented by a period (.). Take a look: <?php 
 // set up some string variables 
 $a = 'the'; 
 $b = 'games'; 
 $c = 'begin'; 
 $d = 'now'; 
 
 // combine them using the concatenation operator 
 // this returns 'the games begin now<br />' 
 $statement = $a.' '.$b.' '.$c.' '.$d.'<br />'; 
 print $statement; 
 ?> Data Types in PHP
  8. Start Up As before, you can concatenate and assign simultaneously,

    as below: <?php 
 
 // define string 
 $str = 'the'; 
 
 // add and assign 
 $str .= 'n'; 
 
 // str now contains "then" 
 echo $str; ?>
  9. Start Up <html> 
 <head></head>
 <body> 
 <form action=“ageProcess.php" method="post">

    
 Enter your age: <input name="age" size="2"> 
 </form> 
 </body> 
 </html> sampleForm1.html Simple Form in PHP (separated files)
  10. Start Up <html> 
 <head></head>
 <body> 
 <?php 
 //

    retrieve form data 
 $age = $_POST['age']; 
 // check entered value and branch 
 if ($age >= 21) { 
 echo 'Come on in, we have alcohol and music awaiting you!'; 
 } 
 if ($age < 21) { 
 echo 'You\'re too young for this club, come back when you\'re a little older'; 
 } 
 ?> 
 </body> 
 </html> ageProcess.php
  11. Start Up GET Vs POST METHOD The official recommendations say

    that "GET" should be used if and only if the form processing is idempotent. Idempotent means which typically means a pure query form. However, problems related to long URLs and non-ASCII character repertoires which can make it necessary to use "POST" even for idempotent processing
  12. Start Up sampleForm2.html <html> 
 <head></head>
 <body> 
 <h2>Today's Special</h2>

    
 <p> 
 <form method="get“action="cooking.php"> 
 <select name="day"> 
 <option value="1">Monday/Wednesday 
 <option value="2">Tuesday/Thursday 
 <option value="3">Friday/Sunday 
 <option value="4">Saturday 
 </select> 
 <input type="submit" value="Send"> 
 </form> 
 </body> 
 </html>
  13. Start Up <html> 
 <head></head>
 <body> <?php 
 // get

    form selection 
 $day = $_GET['day']; 
 // check value and select appropriate item 
 if ($day == 1) { 
 $special = 'Chicken in oyster sauce'; 
 } 
 elseif ($day == 2) { 
 $special = 'French onion soup'; 
 } 
 elseif ($day == 3) { 
 $special = 'Pork chops with mashed potatoes and green salad'; 
 } 
 else { 
 $special = 'Fish and chips'; 
 } 
 ?> Cooking.php
  14. Arrays <?php 
 
 // define an array
 $pizzaToppings =

    array('onion', 'tomato', 'cheese', 'anchovies', 'ham', 'pepperoni'); 
 print_r($pizzaToppings); 
 
 ?>
  15. Arrays [Push and Pull] You can also add an element

    to the end of an existing array with the array_push() function: 
 <?php 
 
 // define an array
 $pasta = array('spaghetti', 'penne', 'macaroni'); 
 
 // add an element to the end 
 array_push($pasta, 'tagliatelle'); 
 
 print_r($pasta); 
 
 ?>
  16. Arrays [Push and Pull] And you can remove an element

    from the end of an array using the interestingly-named array_pop() function. 
 <?php 
 
 // define an array
 $pasta = array('spaghetti', 'penne', 'macaroni'); 
 
 // remove an element from the end 
 array_pop($pasta); 
 
 print_r($pasta); 
 
 ?>
  17. Arrays [implode and Explode] The explode() function splits a string

    into smaller components, based on a user-specified delimiter, and returns the pieces as elements as an array. <?php 
 
 // define CSV string
 $str = 'red, blue, green, yellow'; 
 
 // split into individual words 
 $colors = explode(', ', $str); 
 
 print_r($colors); 
 
 ?>
  18. Arrays [looping the loop] <html> 
 <head></head>
 <body> 
 My

    favourite bands are: 
 <ul> 
 
 <?php 
 
 // define array 
 $artists = array('Metallica', 'Evanescence', 'Linkin Park', 'Guns n Roses'); 
 // loop over it and print array elements 
 for ($x = 0; $x < sizeof($artists); $x++) { 
 echo '<li>'.$artists[$x]; 
 } 
 
 ?> 
 
 </ul> 
 </body> 
 </html>
  19. Arrays [looping the loop] <html> 
 <head></head>
 <body> 
 My

    favourite bands are: 
 <ul> 
 
 <?php 
 
 // define array 
 $artists = array('Metallica', 'Evanescence', 'Linkin Park', 'Guns n Roses'); 
 // loop over it 
 // print array elements 
 foreach ($artists as $a) { 
 echo '<li>'.$a; 
 } 
 
 ?> 
 </ul> 
 </body> 
 </html>
  20. File Handling [read and write] <?php 
 
 // set

    file to read
 $file = '/directory/omelette.txt'; 
 // open file 
 $fh = fopen($file, 'r') or die('Could not open file!'); 
 // read file contents 
 $data = fread($fh, filesize($file)) or die('Could not read file!'); 
 // close file 
 fclose($fh); 
 // print file contents 
 echo $data; 
 
 ?>
  21. File Handling [read and write] <?php 
 
 // set

    file to write
 $file = '/directory/omelette.txt'; 
 // open file 
 $fh = fopen($file, 'w') or die('Could not open file!'); 
 // write to file 
 fwrite($fh, "Look, Ma, I wrote a file!\n") or die('Could not write to file'); // close file 
 fclose($fh); 
 
 ?>
  22. Session Control <?php 
 
 // initialize a session 


    session_start(); 
 
 // this function checks the value of a session variable 
 // and returns true or false 
 function isAdmin() { 
 if ($_SESSION['name'] == 'admin') { 
 return true; 
 } 
 else { 
 return false; 
 } 
 } 
 
 // set a value for $_SESSION['name'] 
 $_SESSION['name'] = "guessme"; 
 // call a function which uses a session variable 
 // returns false here 
 echo isAdmin()."<br />"; 
 
 // set a new value for $_SESSION['name'] 
 $_SESSION['name'] = "admin"; 
 // call a function which uses a session variable 
 // returns true here 
 echo isAdmin()."<br />"; 
 
 ?>
  23. Cookie Control <?php 
 
 if (!isset($_POST['email'])) { 
 //

    if form has not been submitted 
 // display form 
 // if cookie already exists, pre-fill form field with cookie value 
 ?> 
 <html> 
 <head></head> 
 <body> 
 <form action="<?php echo $_SERVER['PHP_SELF']?>" method="post"> 
 Enter your email address: <input type="text" name="email" value="<?php echo $_COOKIE['email']; ?>"> 
 <input type="submit" name="submit"> 
 <?php 
 // also calculate the time since the last submission 
 if ($_COOKIE['lastsave']) { 
 $days = round((time() - $_COOKIE['lastsave']) / 86400); 
 echo "<br /> $days day(s) since last submission"; 
 } 
 ?> 
 </form> 
 </body> 
 </html> 
 <?php 
 } 
 else { 
 // if form has been submitted 
 // set cookies with form value and timestamp 
 // both cookies expire after 30 days 
 if (!empty($_POST['email'])) { 
 setcookie("email", $_POST['email'], mktime()+(86400*30), "/"); 
 setcookie("lastsave", time(), mktime()+(86400*30), "/"); 
 echo "Your email address has been recorded."; 
 } 
 else { 
 echo "ERROR: Please enter your email address!"; 
 } 
 } 
 ?> 
 </body> 
 </html>
  24. Session Control <?php 
 
 // initialize a session 


    session_start(); 
 ?> 
 <html> 
 <head></head> 
 <body> 
 
 <?php 
 if (!isset($_SESSION['name']) && !isset($_POST['name'])) { 
 // if no data, print the form 
 ?> 
 <form action="<?php echo $_SERVER['PHP_SELF']?>" method="post"> 
 <input type="text" name="name"> 
 <input type="submit" name="submit" value="Enter your name"> 
 </form> 
 <?php 
 } 
 else if (!isset($_SESSION['name']) && isset($_POST['name'])) { 
 // if a session does not exist but the form has been submitted 
 // check to see if the form has all required values 
 // create a new session 
 if (!empty($_POST['name'])) { 
 $_SESSION['name'] = $_POST['name']; 
 $_SESSION['start'] = time(); 
 echo "Welcome, " . $_POST['name'] . ". A new session has been activated for you. Click <a href=" . $_SERVER['PHP_SELF'] . ">here</a> to refresh the page."; 
 } 
 else { 
 echo "ERROR: Please enter your name!"; 
 } 
 } 
 else if (isset($_SESSION['name'])) { 
 // if a previous session exists 
 // calculate elapsed time since session start and now 
 echo "Welcome back, " . $_SESSION['name'] . ". This session was activated " . round((time() - $_SESSION['start']) / 60) . " minute(s) ago. Click <a href=" . $_SERVER['PHP_SELF'] . ">here</a> to refresh the page."; 
 } 
 ?> 
 </body> 
 </html>
  25. Integration with Mysql Database <html> 
 <head> 
 <basefont face="Arial">

    
 </head> 
 <body> 
 
 <?php 
 
 // set database server access variables: 
 $host = "localhost"; 
 $user = "test"; 
 $pass = "test"; 
 $db = "testdb"; 
 
 // open connection 
 $connection = mysql_connect($host, $user, $pass) or die ("Unable to connect!"); 
 
 // select database 
 mysql_select_db($db) or die ("Unable to select database!"); 
 
 // create query 
 $query = "SELECT * FROM symbols"; 
 
 // execute query 
 $result = mysql_query($query) or die ("Error in query: $query. ".mysql_error()); 
 
 // see if any rows were returned 
 if (mysql_num_rows($result) > 0) { 
 // yes 
 // print them one after another 
 echo "<table cellpadding=10 border=1>"; 
 while($row = mysql_fetch_row($result)) { 
 echo "<tr>"; 
 echo "<td>".$row[0]."</td>"; 
 echo "<td>" . $row[1]."</td>"; 
 echo "<td>".$row[2]."</td>"; 
 echo "</tr>"; 
 } 
 echo "</table>"; 
 } 
 else { 
 // no 
 // print status message 
 echo "No rows found!"; 
 } 
 
 // free result set memory 
 mysql_free_result($result); 
 
 // close connection 
 mysql_close($connection); 
 
 ?> 
 
 </body> 
 </html>