SlideShare a Scribd company logo
1 of 78
Download to read offline
PHP
    IT1 Course Slide
       Instructor:
     Majid Taghiloo

١
Server-Side Dynamic Web Programming
• CGI is one of the most common approaches to server-side programming
         Universal support: (almost) Every server supports CGI programming. A great deal of ready-to-use
         CGI code. Most APIs (Application Programming Interfaces) also allow CGI p g
                               ( pp            g         g            )               programming.g
         Choice of languages: CGI is extremely general, so that programs may be written in nearly any
         language. Perl is by far the most popular, with the result that many people think that CGI means
         Perl. But C, C++, Ruby, and Python are also used for CGI programming.
         Drawbacks: A separate process is run every time the script is requested. A distinction is made
         between HTML pages and code.
• Other server-side alternatives try to avoid the drawbacks
     Server-Side Includes (SSI): Code is embedded in HTML pages, and evaluated on the server while
         the pages are being served. Add dynamically generated content to an existing HTML page, without
         having to serve the entire page via a CGI program
                                                     program.
         Active Server Pages (ASP, Microsoft) : The ASP engine is integrated into the web server so it does
         not require an additional process. It allows programmers to mix code within HTML pages instead of
         writing separate programs. (Drawback(?) Must be run on a server using Microsoft server software.)
                          programs                                                                software )
         Java Servlets (Sun): As CGI scripts, they are code that creates documents. These must be
         compiled as classes which are dynamically loaded by the web server when they are run.
         Java Server Pages (
                         g (JSP): Like ASP, another technology that allows developers to embed Java in
                                   )          ,                gy                   p
         web pages.
     ٢
PHP
• developed in 1995 by Rasmus Lerdorf (member of the Apache Group)
     originally designed as a tool for tracking visitors at Lerdorf's Web site
     within 2 years, widely used in co ju c o with the Apache se e
              yea s, de y            conjunction         e pac e server
     developed into full-featured, scripting language for server-side programming
     free, open-source
     server plug-ins exist for various servers
            plug ins
     now fully integrated to work with mySQL databases

• PHP is similar to JavaScript, only it’s a server-side l
      i i il t J S i t l it’                           id language
     PHP code is embedded in HTML using tags
     when a page request arrives, the server recognizes PHP content via the file extension (.php
     or .phtml)
     the server executes the PHP code, substitutes output into the HTML page
     the resulting page is then downloaded to the client
     user never sees the PHP code, only the output in the page

• The acronym PHP means (in a slightly recursive definition)
     PHP: Hypertext Preprocessor
     ٣
What do You Need?
•   Our server supports PHP
    O                   PHP
     – You don't need to do anything special! *
     – You don't need to compile anything or install any extra tools!
     – Create some .php f l in your web d
                      h files          b directory ‐ and the server will parse them f
                                                        d h           ll        h   for
       you.
          * Slightly different rules apply when dealing with an SQL database (as will be explained when we get to that point).

•   Most servers support PHP
     – Download PHP for free here: http://www.php.net/downloads.php
     – Download MySQL for free here: http://www mysql com/downloads/index html
                                      http://www.mysql.com/downloads/index.html
     – Download Apache for free here: http://httpd.apache.org/download.cgi


     (Note: All of this is already present on the CS servers, so you need not do any
       installation yourself to utilize PHP on our machines.)


     ۴
Help with PHP
    Loads of information, including help on individual PHP
                  functions may be found at
                     http://uk.php.net/
                     h // k h           /




۵
Basic PHP syntax
A PHP scripting block always starts with <?php and ends with ?> A PHP scripting block
                                                             ?>.
can be placed (almost) anywhere in an HTML document.
 <html>
 <!‐‐ hello.php COMP519 ‐‐>                                                   print and echo
                                                                                 i t      h
 <head><title>Hello World</title></head>
 <body>                                                                       for output
 <p>This is going to be ignored by the PHP interpreter.</p>

  <?php echo ‘<p>While this is going to be parsed.</p>‘; ?>                    a semicolon (;) at the
  <p>This will also be ignored by PHP.</p>                                     end of each statement
  <?php i t(‘< >H ll
  <? h print(‘<p>Hello and welcome t <i> </i> page!</p>');
                         d l       to <i>my</i>   !</ >')
  ?>

  <?php

  //This is a comment
                                                                             // for a single-line comment
                                                                                      single line
  /*                                                                         /* and */ for a large
   This is
   a comment
                                                                             comment block.
   block
  */
  ?>

 </body>
 </html>

     ۶
                              The server executes the print and echo statements, substitutes output.
Scalars
All variables in PHP start with a $ sign symbol. A variable's type is determined by the
                                  $ g y                        yp                 y
context in which that variable is used (i.e. there is no strong‐typing in PHP).
 <html><head></head>
 <!‐‐ scalars.php
 <! scalars php COMP519 ‐‐>     >
 <body> <p>
 <?php
 $foo = true; if ($foo) echo "It is TRUE! <br /> n";
 $txt='1234'; echo "$txt <br /> n";
                                                                   Four scalar types:
 $a = 1234; echo "$a <br /> n";                                   boolean
                                                                   b l
 $a = ‐123;
 echo "$a <br /> n";                                                 true or false
 $a = 1.234;
 echo "$a <br /> n";
        $a br / n ;
                                                                   integer,
 $a = 1.2e3;                                                       float,
 echo "$a <br /> n";
 $a = 7E‐10;                                                        floating point numbers
 echo "$a <br /> n";
 echo 'Arnold once said: "I'll be back , "<br /> n";
        Arnold             I ll back"' <br n ;
                                                                   stringg
 $beer = 'Heineken';                                                single quoted
 echo "$beer's taste is great <br /> n";
 $str = <<<EOD                                                      double quoted
 Example of string
 spanning multiple lines
 using “heredoc” syntax.
 EOD;
 echo $str;
 ?>
 </p>
 </body>
 </html>
      ٧
Arrays
                                                            y
An array in PHP is actually an ordered map. A map is a type that maps values to keys.
                                                                 array() = creates arrays
 <?php
 $arr = array("foo" => "bar", 12 => true);                       key = either an integer or a string.
 echo $arr["foo"]; // bar
 echo $arr[12]; // 1                                             value = any PHP type.
 ?>

                                                                  if no key given (as in example), the PHP
 <?php
 array(5 => 43, 32, 56, "b" => 12);
                                                                  interpreter uses (maximum of the integer indices +
 array(5 => 43, 6 => 32, 7 => 56, "b" => 12);
     y(                                    )                      1).
 ?>
                                                                  if an existing key, its value will be overwritten.


  <?php
     p p
  $arr = array(5 => 1, 12 => 2);
                                                                                            can set values in an array
  foreach ($arr as $key => $value) { echo $key, ‘=>’,
                          $value); }
  $arr[] = 56; // the same as $arr[13] = 56;                                    unset() removes a key/value pair
  $arr[ x ]
  $arr["x"] = 42; // adds a new element
  unset($arr[5]); // removes the element
  unset($arr); // deletes the whole array
  $a = array(1 => 'one', 2 => 'two', 3 => 'three');
                                                                               array_values() makes reindexing effect
  unset($a[2]);                                                                (indexing numerically)
  $b = array_values($a);
                l ($ )
  ?>

      ٨                                                                             *Find more on arrays
Constants
A constant is an identifier (name) for a simple value. A constant is case‐sensitive by
A constant is an identifier (name) for a simple value A constant is case sensitive by
default. By convention, constant identifiers are always uppercase.


  <?php

  // Valid constant names
  define("FOO", "something");
  define("FOO2", "something else");
  define("FOO_BAR", "something more");

  // Invalid constant names (they shouldn’t start
                                  shouldn t                     You can access constants
  // with a number!)
                                                                anywhere in your script
  define("2FOO", "something");                                  without regard to scope.
  // This is valid, b t should b avoided:
     Thi i     lid but h ld be      id d
  // PHP may one day provide a “magical” constant
  // that will break your script

  define("__FOO__", "something");

  ?>




   ٩
Operators                Example Is the same as
•   Arithmetic Operators: +, ‐, *,/ , %, ++, ‐‐             x+=y          x=x+y
                                                            x‐=y          x=x‐y
•   Assignment Operators: =, +=, = =, /=,
    Assignment Operators: = += ‐=, *= /= %=                 x*=y
                                                             *            x=x*y
                                                                             *
                                                            x/=y          x=x/y
                                                            x%=y          x=x%y



•   Comparison Operators: ==, !=, >, <, >=, <=
•   Logical Operators: &&, ||, !
•   String Operators: . and .= (for string concatenation)



    $a = "Hello ";
    $b = $a . "World!"; // now $b contains "Hello World!"

    $a = "Hello ";
    $a .= "World!";


     ١٠
Conditionals: if else
Can execute a set of code depending on a condition

  <html><head></head>                           if (condition)
                                                   (         )
  <!‐‐ if‐cond.php COMP519 ‐‐>
  <body>                                        code to be executed if condition
                                                is true;
  <?php
  $d=date("D");
  $d d (" ")                                    else
  echo $d, “<br/>”;                             code to be executed if condition
  if ($d=="Fri")
      echo "Have a nice weekend! <br/>";
                                                is false;
  else
    l
      echo "Have a nice day! <br/>";

  $x=10;
                                                date() is a built-in PHP function
  if ($x==10)
     ($ 10)                                     that can be called with many
  {                                             different parameters to return the
      echo "Hello<br />";
      echo "Good morning<br />";                date (and/or local time) in
  }                                             various f
                                                    i    formats
                                                               t
  ?>
                                                In this case we get a three letter
  </body>
   /b d
  </html>
                                                string for the day of the week.
       ١١
Conditionals: switch
Can select one of many sets of lines to execute

  <html><head></head>
  <body>
  <!–‐ switch‐cond.php COMP519 ‐‐>                switch (expression)
  <?php
  $x = rand(1,5); // random integer
                                                  {
  echo “x = $ <br/><br/>”;
            $x     /    /                         case label1:
  switch ($x)                                       code to be executed if expression =
  {
  case 1:
                                                  label1;
    echo "Number 1";  ;                             break;
    break;                                        case label2:
  case 2:
    echo "Number 2";
                                                    code to be executed if expression =
    break;                                        label2;
  case 3:                                           break;
    echo "Number 3";
    break;
                                                  default:
  default:                                          code to be executed
    echo "No number between 1 and 3";               if expression is different
    break;
    b k
  }
                                                    from both label1 and label2;
  ?>                                                break;
                                                  }
  </body>
  </html>

    ١٢
Looping: while and do‐while
Can loop depending on a condition
Can loop depending on a condition

   <html><head></head>                                            <html><head></head>
   <body>
       y                                                          <body>
                                                                      y

   <?php                                                          <?php
   $i=1;                                                          $i=0;
   while($i <= 5)                                                 do
   {                                                              {
     echo "The number is $i <br />";                                $i++;
     $i++;                                                          echo "The number is $i <br />";
   }                                                              }
   ?>                                                             while($i <= 10);
                                                                  ?>
   </body>
   </html>                                                        </body>
                                                                  </html>




   loops through a block of code if and as long as, a specified
                                 if,            as
   condition is true                                                 loops through a block of code once, and then repeats the
                                                                     loop as long as a special condition is true (so will always
                                                                     execute at least once)




    ١٣
Looping: for and foreach
                          p g
Can loop depending on a "counter"


  <?php                                              <?php
  for ($i=1; $i<=5; $i++)                            $a_array = array(1, 2, 3, 4);
  {                                                  foreach ($a_array as $value)
  echo "Hello World!<br />";                         {
  }                                                    $value = $value * 2;
  ?>                                                   echo “$value <br/> n”;
                                                     }
                                                     ?>


  loops through a block of code a specified number
  of times                                            <?php
                                                      $a_array=array( a b c );
                                                      $a array=array("a","b","c");
                                                      foreach ($a_array as $key => $value)
                                                      {
                                                        echo $key." = ".$value."n";
                                                      }
                                                      ?>



                                                         loops through a block of code for each element in an
                                                            p       g
                                                         array

    ١۴
User Defined Functions
Can define a function using syntax such as the following:

  <?php
  function foo($arg 1, $arg 2, /* ..., */ $arg n)
              ($ g_ , $ g_ , / , / $ g_ )                                   Can also define conditional functions, functions
                                                                                                         functions
  {
    echo "Example function.n";
                                                                            within functions, and recursive functions.
    return $retval;
  }
  ?>


Can return a value of any type

    <?php                                                    <?php
    function square($num)                                    function small_numbers()
    {                                                        {
      return $num * $num;                                       return array (0, 1, 2);
    }                                                        }
    echo square(4);                                          list ($zero, $one, $two) = small_numbers();
    ?>                                                       echo $zero, $one, $two;
                                                             ?>


   <?php
   function takes_array($input)
   {
     echo "$input[0] + $input[1] = ", $input[0]+$input[1];
           $input[0]
   }
    takes_array(array(1,2));
   ?> ١۵
Variable Scope
The scope of a variable is the context within which it is defined.

  <?php
    ? h
  $a = 1; /* limited variable scope */
  function Test()
  {
                                                                          The scope is local within functions,
     echo $
       h $a;                                                                    and hence the value of $a is
    /* reference to local scope variable */                               undefined in the “echo” statement.
  }
  Test();
  ?>
  ?


                                                            <?php
  <?php
     p p                                                    function Test()
  $a = 1;                                                   {
  $b = 2;                            global                   static $a = 0;                static
  function Sum()                                              echo $a;
  {                                  refers to its global     $a++;                         does not lose its value.
    global $a $b;
           $a,                       version.
                                     version                }
    $b = $a + $b;                                           Test1();
  }                                                         Test1();
  Sum();                                                    Test1();
  echo $b;                                                  ?>
  ?>


     ١۶
Including Files
The include() statement includes and evaluates the specified file.


                                                       <?php
  vars.php
                                                       function foo()
  <?php
                                                       {
                                                         global $color;
  $color = 'green';
  $fruit = 'apple';
                                                           include ('vars.php‘);
  ?>
                                                           echo "A $color $fruit";
                                                       }
  test.php
  <?php
                                                       /
                                                       /* vars.php is in the scope of foo() so *
                                                               p p              p        ()
                                                        * $fruit is NOT available outside of this *
  echo "A $color $fruit"; // A
                                                        * scope. $color is because we declared it *
                                                        * as global.                 */
  include 'vars.php';
                                                       foo();          // A green apple
  echo "A $color $fruit"; // A green apple
                                                       echo "A $color $fruit"; // A green
  ?>
                                                       ?>


        *The scope of variables in “included” files depends on where the “include” file is added!
       ١٧
        You can use the include_once, require, and require_once statements in similar ways.
PHP Information
The phpinfo() function is used to output PHP information about the version installed on the 
   server, parameters selected when installed, etc.
         , parameters selected when installed, etc.



  <html><head></head>
                                                     INFO_GENERAL                  The configuration line,
  <!– info.php COMP519
                                                                                   php.ini location,
  <body>
                                                                                   build date,
  <?php
                                                                                   Web Server,
  // Show all PHP information
                                                                                   System and more
  phpinfo();
  ?>
                                                     INFO_CREDITS                  PHP 4 credits
  <?php
                                                     INFO_CONFIGURATION            Local and master values
  // Show only the general information
                                                                                   for php directives
  phpinfo(INFO_GENERAL);
  phpinfo(INFO GENERAL);
  ?>
                                                     INFO_MODULES                  Loaded modules
  </body>
  </html>
                                                     INFO_ENVIRONMENT              Environment variable
                                                                                   information
                                                     INFO_VARIABLES                All predefined variables
                                                                                   from EGPCS

                                                     INFO_LICENSEPHP license information
                                                     INFO_ALL
                                                     INFO ALL    Shows all of the above (default)


     ١٨
Server Variables
The $_SERVER array variable is a reserved variable that contains all server information. 


   <html><head></head>
    h l h d /h d
   <body>

   <?php
   echo "Referer: " . $_SERVER["HTTP_REFERER"] . "<br />";
                       _        [     _       ]
   echo "Browser: " . $_SERVER["HTTP_USER_AGENT"] . "<br />";
   echo "User's IP address: " . $_SERVER["REMOTE_ADDR"];
   ?>

   </body>
   </html>




  The $_SERVER is a super global variable, i.e. it's available in all scopes of a PHP script.




     ١٩
File Open

The fopen("file_name","mode") function is used to open files in PHP.

  r           Read only.                       r+                        Read/Write.
  w           Write only.                     w+                         Read/Write.
  a           Append.
              Append                          a+                         Read/Append.
                                                                         Read/Append
  x           Create and open for write only. x+                         Create and open for read/write.


   <?php                                     For w, and a, if no file exists, it tries to create it (use with caution, i.e.
   $fh=fopen("welcome.txt","r");             check that this is the case, otherwise you’ll overwrite an existing file).
   ?>

                                              For x if a file exists, it returns an error.
  <?php
  if                                               If th f
                                                      the fopen() f ti iis unable to open the specified file, it
                                                                () function   bl t        th      ifi d fil
  ( !($fh=fopen("welcome.txt","r")) )              returns 0 (false).
  exit("Unable to open file!");
  ?>


      ٢٠
File Workings
fclose() closes a file.
                                                          feof() determines if the end is true
                                                                                          true.

fgetc() reads a single character                          fgets() reads a line of data

fwrite(), fputs () writes a string with and without n
      (), p                      g
                                                          file() reads entire f into an array
                                                                              file


   <?php                                                           <?php
   $myFile = "welcome.txt";
               welcome.txt ;                                       $myFile = "welcome.txt";
                                                                               welcome.txt ;
   if (!($fh=fopen($myFile,'r')))                                  $fh = fopen($myFile, 'r');
   exit("Unable to open file.");                                   $theData = fgets($fh);
   while (!feof($fh))                                              fclose($fh);
   {                                                               echo $theData;
   $x=fgetc($fh);                                                  ?>
   echo $x;
   }
   fclose($fh);
   ?>                                                              <?php
                                                                      p p
                                                                   $myFile = "testFile.txt";
                                                                   $fh = fopen($myFile, 'a') or die("can't open file");
                                                                   $stringData = "New Stuff 1n";
   <?php                                                           fwrite($fh, $stringData);
   $lines = fil (' l
   $li      file('welcome.txt');
                             ')                                    $stringData = "New Stuff 2n";
                                                                                   New       2n ;
   foreach ($lines as $l_num => $line)                             fwrite($fh, $stringData);
   {                                                               fclose($fh);
    echo "Line #{$l_num}:“ .$line.”<br/>”;                         ?>
   }
   ?>

      ٢١
Form Handling
Any form element is automatically available via one of the built‐in PHP variables (provided the element has a “name” defined with 
  y o e e e t s auto at ca y a a ab e a o e o t e bu t                   a ab es (p o ded t e e e e t as a a e de ed t
     it).



  <html>
  <‐‐ form.html COMP519 ‐‐>
  <body>
  <form action="welcome.php" method="POST">
  Enter your name: <input type="text" name="name" /> <br/>
  Enter your age: <input type="text" name="age" / <br/>
                              "    "      " " /> b /
  <input type="submit" /> <input type="reset" />
  </form>
  </body>
  </html>




   <html>                                                                             $_POST
                                                                                       _
   <!–‐ welcome.php COMP 519 ‐‐>
    !     l      h
                                                                                      contains all POST data.
   <body>
                                                                                      $_GET
   Welcome <?php echo $_POST["name"].”.”; ?><br />
                                                                                      contains all GET data.
   You are <?php echo $_POST["age"]; ?> years old!

   </body>
   </html>




      ٢٢
Cookie Workings
setcookie(name,value,expire,path,domain) creates cookies.
      ki (       l      i      h d   i )            ki

 <?php
 setcookie("uname", $_POST["name"], time()+36000);
 ?>
 <html>
 <body>                                                                  NOTE:
 <p>                                                                     setcookie() must appear
 Dear <?php echo $_POST["name"] ?>, a cookie was set on this
                                                                         BEFORE <html> (or any output)
 page! The cookie will be active when the client has sent the
 cookie back to the server.                                              as it’s part of the header
 </p>                                                                    information sent with the page.
 </body>
 </html>



  <html>
  <body>                                                        $_COOKIE
  <?php                                                         contains all COOKIE data.
  if ( isset($_COOKIE["uname"]) )
  echo "Welcome " . $_COOKIE["uname"] . "!<br />";
  else                                                          isset()
  echo "You are not logged in!<br />";                          finds out if a cookie is set
  ?>
  </body>
  </html>
    /
                                                                 use the cookie name as a variable


    ٢٣
Getting Time and Date
date() and time () formats a time or a date
                   formats a time or a date.

  <?php
  //Prints something like Monday
                     like:
  echo date("l");
                                                                                       date() returns a string formatted according to
  //Like: Monday 15th of January 2003 05:51:38 AM
                                                                                       the specified format.
  echo date("l jS of F Y h:i:s A");

  //Like: Monday the 15th
  echo date("l the jS");
  ?>




  <?php
     p p
  $nextWeek = time() + (7 * 24 * 60 * 60);
            // 7 days; 24 hours; 60 mins; 60secs                                                     time() returns current Unix
  echo 'Now: '. date('Y‐m‐d') ."n";                                                                 timestamp
  echo 'Next Week: '. date('Y‐m‐d', $nextWeek) ."n";
  ?>




   *Here is more on date/time formats: http://uk.php.net/manual/en/function.date.php

     ٢۴
Required Fields in User‐Entered Data
A multipurpose script which asks users for some basic contact information and then checks to 
     l                   h h k          f       b               f           d h     h k
see that the required fields have been entered.

  <html>
  <!‐‐ form_checker.php COMP519 ‐‐>
  <head>
  <title>PHP Form example</title>
  </head>
  <body>
  <?php
  /*declare some functions*/



                                                   Print Function
                                                   P i t F ti
  function print_form($f_name, $l_name, $email, $os)
  {
  ?>

  <form action="form_checker.php" method=“POST">
  First Name: <input type="text" name="f_name" value="<?php echo $f_name?>“ /> <br/>
  Last Name <b>*</b>:<input t
  L tN       <b>*</b> <i    t type="text" name="l_name" value="<?php echo $l
                                   "t t"       "l      " l    "<? h    h $l_name?>“ /> <b />
                                                                                   ?>“ <br/>
  Email Address <b>*</b>:<input type="text" name="email" value="<?php echo $email?>“ /> <br/>
  Operating System: <input type="text" name="os" value="<?php echo $os?>“ /> <br/><br/>
  <input type="submit" name="submit" value="Submit“ /> <input type=“reset“ />
  </form>

  <?php
  } //** end of “print_from” function
       ٢۵
Check and Confirm Functions
     function check_form($f_name, $l_name, $email, $os)
     {
       if (!$l_name||!$email){
       echo "<h3>You are missing some required fields!</h3>";
       print_form($f_name, $l_name, $email, $os);
       }
       else{
        confirm_form($f_name, $l_name, $email,
        confirm form($f name $l name $email $os);
       }
     } //** end of “check_form” function




     function confirm_form($f_name, $l_name, $email, $os)
     {
     ?>

     <h2>Thanks! Below is the information you have sent to us.</h2>
     <h3>Contact Info</h3>

     <?php
     echo "N
       h "Name: $f$f_name $l
                           $l_name <br/>";
                                     b/ "
     echo "Email: $email <br/>";
     echo "OS: $os";
     } //** end of “confirm_form” function




٢۶
Main Program
/*Main Program*/

if (!$_POST["submit"])
{
?>

<h3>Please enter your information</h3>
<p>Fields with a "<b>*</b>" are required.</p>

<?php
 print_form("","","","");
}
else{
 check_form($_POST["f_name"],$_POST["l_name"],$_POST["email"],$_POST["os"]);
}
?>


</body>
</html>




  ٢٧
Introduction to SQL
SQL is an ANSI (American National Standards Institute) standard computer language 
for accessing and manipulating databases.
•    SQL stands for Structured Query Language
•    using SQL can you can
       – access a database
       – execute queries, and retrieve data
       – insert, delete and update records
•    SQL works with database programs like MS Access, DB2, Informix, MS SQL Server, Oracle, Sybase, mySQL, etc.




Unfortunately, there are many different versions. But, they must support the same major keywords in a similar manner such as
SELECT, UPDATE, DELETE, INSERT, WHERE, etc.

Most of the SQL database programs also have their own proprietary extensions!




  ٢٨
SQL Database Tables
A database most often contains one or more tables. Each table is identified by a
name (e.g. "Customers" or "Orders"). Tables contain records (rows) with data.

For example, a table called "Persons":

   LastName
   L tN              FirstName
                     Fi tN             Address
                                       Add               City
                                                         Cit
   Hansen            Ola               Timoteivn 10      Sandnes
   Svendson          Tove              Borgvn 23         Sandnes
   Pettersen         Kari              Storgt 20         Stavanger


The table above contains three records (one for each person) and four columns (LastName,
FirstName, Address, and City).
SQL Queries
With SQL, you can query a database and have a result set returned.

A query like thi
        lik this:

SELECT LastName FROM Persons;


gives a result set like this:

LastName
Hansen
 a se
Svendson
Pettersen
                                The mySQL database system requires a semicolon at the end of
                                the SQL statement!
SQL Data Languages
The query and update commands together form the Data Manipulation Language
(DML) part of SQL:
• SELECT - extracts data from a database table
• UPDATE - updates data in a database table
• DELETE - deletes data from a database table
• INSERT INTO - inserts new data into a database table


The Data Definition Language (DDL) part of SQL permits database tables to be created
or deleted:
• CREATE TABLE - creates a new database table
• ALTER TABLE - alters (changes) a database table
• DROP TABLE - deletes a database table
• CREATE INDEX - creates an index (search key)
• DROP INDEX - deletes an index


                  *Here we will use some of them in mySQL
  ٣١
Logging into mySQL Server
You
Y can l i
      log into our mySQL server f
                     SQL        from Li
                                     Linux b typing i the prompt
                                           by   i in h

  bash‐2.05b$ mysql ‐h mysql martin –u martin


  Welcome to the MySQL monitor. Commands end with ; or g.
  Your MySQL connection id is 209201 to server version: 5.0.22

  Type 'help;' or 'h' for help. Type 'c' to clear the buffer.

  mysql>

From here you can create modify and drop tables, and modify the data in your tables
                     create, modify,        tables                             tables.
But first, you must specify which database on the server you want to use (you have only
one, however).

    mysql> use martin;



    Database changed
  ٣٢
Technical note
• Y probably d ’t need t worry about thi b t th
  You   b bl don’t   d to       b t this, but thought I would
                                                   ht      ld
  mention it here…

          Most books and on‐line tutorials assume the database server is
     running on the same machine as everything else, and that the user
     is "root".
         root
          Neither of these are true here. Wherever you see "localhost",
     replace it by "mysql" Wherever you see "root", replace it with your
     username.


(Ignore this if you don’t understand it for now, or are not consulting
   other references.)

٣٣
Creating a Table
You
Y can create a table you might use f the upcoming project. For example,
                 bl       i h      for h      i      j              l

mysql> CREATE TABLE students(
                                                              Hit Enter after each line (if you
  ‐> num INT NOT NULL AUTO_INCREMENT,
                                                              want). MySQL doesn’t try to
  ‐> f_name VARCHAR(48),                                      interpret the command itself until
  ‐> l_name VARCHAR(48),                                      it sees a semicolon (;)
  ‐> student_id INT,                                          (The “->” characters you see are
  ‐> email VARCHAR(48),                                       not typed by you.)
  ‐> PRIMARY KEY(num));




Query OK, 0 rows affected (0.02 sec)


 *If the server gives you a big ERROR, just try again from the top!

 ٣۴
Viewing The Table Structure
Use DESCRIBE to see the structure of a table

 mysql> DESCRIBE students;



 +‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐+‐‐‐‐‐+‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐+
 | Field | Type             | Null | Key | Default | Extra            |
 +‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐+‐‐‐‐‐+‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐+
 | num        | int(11) | NO | PRI | NULL | auto_increment |
 | f_name | varchar(48) | YES | | NULL |                               |
 | l_name | varchar(48) | YES | | NULL |                               |
 | student_id | int(11) | YES | | NULL |                             |
 | email | varchar(48) | YES | | NULL |                              |
 +‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐+‐‐‐‐‐+‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐+




  ٣۵
Inserting Data
Using INSERT INTO you can insert a new row into your table. For example,
                                                     table      example


    mysql> INSERT INTO students
      ‐> VALUES(NULL,’Russell’,’Martin’,396640,‘martin@csc.liv.ac.uk');




      Query OK, 1 row affected (0.00 sec)


Using SELECT FROM you select some data from a table.
    g             y


      mysql> SELECT * FROM students;




      +‐‐‐‐‐+‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐+
      | num | f_name | l name | student id | email
                f name l_name student_id                             |
      +‐‐‐‐‐+‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐+
      | 1 | Russell | Martin | 396640 | martin@csc.liv.ac.uk |
      +‐‐‐‐‐+‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐+
      1 row in set (0.00 sec)


    ٣۶
Inserting Some More Data
You
Y can repeat i
           t inserting until all d t i entered i t th t bl
                  ti     til ll data is t d into the table.

mysql> INSERT INTO students
  ‐> VALUES(NULL,‘James',‘Bond',007,'bond@csc.liv.ac.uk');
Query OK, 1 row affected (0.01 sec)


mysql> SELECT * FROM students;
+‐‐‐‐‐+‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐+
| num | f_name | l_name | student_id | email                   |
+‐‐‐‐‐+‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐+
| 1 | Russell | Martin | 396640 | martin@csc.liv.ac.uk |
| 2 | James | Bond |                 7 | bond@csc liv ac uk |
                                         bond@csc.liv.ac.uk
+‐‐‐‐‐+‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐+
2 rows in set (0.00 sec)




            Note: The value “NULL” in the “num” field is automatically replaced by the SQL interpreter as the
            “auto increment” option was selected when the table was defined
             auto_increment                                            defined.

   ٣٧
Getting Data Out of the Table
•    The SELECT command is the main way of getting data out of a table or set of
                                                                 table,
     tables.
               SELECT * FROM students;
     Here the asterisk means to select (i.e. return the information in) all columns.


     You can specify one or more columns of data that you want, such as
               SELECT f name,l name FROM students;
                      f_name,l_name
      +---------+--------+
      | f_name | l_name |
      +---------+--------+
      | Russell | Martin |
      | James   | Bond   |
      +---------+--------+
      2 rows in set (0.00 sec)


٣٨
Getting Data Out of the Table (cont.)
• You can specify other information that you want in the
  query using the WHERE clause
                  WHERE clause.
     SELECT * FROM students WHERE l_name=‘Bond’;
    +-----+---------+--------+------------+----------------------+
   | num | f_name | l_name | student_id | email                 |
   +-----+---------+--------+------------+----------------------+
   |   2 | James   | Bond   |          7 | bond@csc.liv.ac.uk   |
   +-----+---------+--------+------------+----------------------+
   1 row in set (0.00 sec)



    SELECT student_id, email FROM students WHERE
  l_name Bond ;
  l name=‘Bond’;
   +------------+----------------------+
   | student_id | email                |
   +------------+----------------------+
   |          7 | bond@csc.liv.ac.uk
                      @                |
   +------------+----------------------+
   1 row in set (0.00 sec)
  ٣٩
Altering the Table
The
Th ALTER TABLE statement i used to add or d
                         is   d     dd drop columns i an existing table.
                                              l     in     i i      bl

 mysql> ALTER TABLE students ADD date DATE;



 Query OK, 2 rows affected (0.00 sec)
       OK                  (0 00
 Records: 2 Duplicates: 0 Warnings: 0


mysql> SELECT * FROM students;
+‐‐‐‐‐+‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐+
| num | f name | l name | student id | email
          f_name l_name student_id                                    | date |
+‐‐‐‐‐+‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐+
| 1 | Russell | Martin | 396640 | martin@csc.liv.ac.uk | NULL |
| 2 | James | Bond |                 7 | bond@csc liv ac uk | NULL |
                                         bond@csc.liv.ac.uk
+‐‐‐‐‐+‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐+
2 rows in set (0.00 sec)


  ۴٠
Updating the Table
 The UPDATE statement is used to modify data in a table
                                                  table.

mysql> UPDATE students SET date='2007‐11‐15' WHERE num=1;



Query OK, 1 row affected (0.01 sec)
      OK                 (0 01
Rows matched: 1 Changed: 1 Warnings: 0



mysql> SELECT * FROM students;
+‐‐‐‐‐+‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐+
| num | f name | l name | student id | email
          f_name l_name student_id                                     | date   |
+‐‐‐‐‐+‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐+
| 1 | Russell | Martin | 396310 | martin@csc.liv.ac.uk | 2007‐11‐15 |
| 2 | James | Bond |                 7 | bond@csc.liv.ac.uk | NULL            |
+‐‐‐‐‐+‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐+
2 rows in set (0.00 sec)


        Note that the default date format is “YYYY‐MM‐DD” and I don’t believe this
   ۴١
        default setting can be changed.
Deleting Some Data
The DELETE statement is used to delete rows in a table.

 mysql> DELETE FROM students WHERE l_name='Bond';



 Query OK, 1 row affected (0.00 sec)


 mysql> SELECT * FROM students;
 +‐‐‐‐‐+‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐+
 | num | f_name | l_name | student_id | email                           | date |
 +‐‐‐‐‐+‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐+
 | 1 | Russell | Martin | 396310 | martin@csc.liv.ac.uk | 2006‐11‐15 |
 +‐‐‐‐‐+‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐+
 1 row in set (0.00 sec)



  ۴٢
The Final Table
We’ll first add another column, update the (only) record, then insert more
                              , p          ( y)         ,
data.

mysql> ALTER TABLE students ADD gr INT;
 yq                             g     ;
Query OK, 1 row affected (0.01 sec)
Records: 1 Duplicates: 0 Warnings: 0
mysql> SELECT * FROM students;
+‐‐‐‐‐+‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐+
| num | f_name | l_name | student_id | email                            | date     | gr |
+‐‐‐‐‐+‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐+
| 1 | Russell | Martin | 396310 | martin@csc.liv.ac.uk | 2007‐11‐15 | NULL |
+
+‐‐‐‐‐+‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐+
      +         +        +            +                      +            +      +
1 row in set (0.00 sec)
mysql> UPDATE students SET gr=3 WHERE num=1;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> SELECT * FROM students;
+‐‐‐‐‐+‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐+
| num | f_name | l_name | student_id | email                            | date     | gr |
+‐‐‐‐‐+‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐+
| 1 | Russell | Martin | 396310 | martin@csc.liv.ac.uk | 2007‐11‐15 | 3 |
+‐‐‐‐‐+‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐+
1 row in set (0.00 sec)

mysql> INSERT INTO students VALUES(NULL,‘James',‘Bond',007,'bond@csc.liv.ac.uk‘,‘2007‐11‐15’, 1);
. . ۴٣
    .
The Final Table (cont.)
                                                                                                      . . .
                                                                                                      . . .
         mysql> INSERT INTO students VALUES(NULL,‘Hugh,‘Milner',75849789,‘hugh@poughkeepsie.ny‘,
                                                                           CURRENT_DATE, 2);

         Note:      CURRENT_DATE is a built-in SQL command which (as expected)
                                          gives the current (local) date.


                                                                           mysql> SELECT * FROM students;
    +-----+---------+----------+------------+----------------------------+------------+------+
    | num | f_name     | l_name       | student_id | email                         | date          | gr
                                                                                                     g          |
    +-----+---------+----------+------------+----------------------------+------------+------+
|        1 | Russell | Martin     |         396310 | martin@csc.liv.ac.uk         | 2007-11-15 |          3 |
|        5 | Kate     | Ash       |         124309 | kate@ozymandius.co.uk        | 2007-11-16 |          3 |
    |     3 | James    | Bond         |           7 | bond@csc.liv.ac.uk           | 2007-11-15 |          1|
|        4 | Bob      | Jones     |         12190 | bob@nowhere.com               | 2007-11-16 |          3 |
|        6 | Pete     | Lofton    |             76 | lofton@iwannabesedated.com | 2007-11-17 |            2 |
    |     7 | Polly   | Crackers |             1717 | crackers@polly.org           | 2007-11-17 |          1|
|        8 | Hugh     | Milner    |       75849789 | hugh@poughkeepsie.ny         | 2007-11-17 |          2 |
    +-----+---------+----------+------------+----------------------------+------------+------+
                                                                                7 rows in set (0.00 sec)
                                                                                              mysql> exit
    ۴۴
                                                                                                           Bye
Other SQL Commands
• SHOW tables; gives a list of tables that have been defined in the database
• ALTER TABLE students DROP email; would drop the “email” column from all
  records
• DROP TABLE students; deletes the entire “students” table, and its definition (use
                                              students                          (use 
  the DROP command with extreme care!!)
• DELETE FROM students; removes all rows from the “students” table (so once 
  again, use the DELETE command with great caution), the table definition remains
  to be used again
• A more useful command is something like
        DELETE FROM students WHERE (num > 5) AND (num <= 10);
  which selectively deletes students based on their “num” values (for example)
                                                     num              example).

•    HELP; gives the SQL help
•    HELP DROP; gives help on the DROP command, etc.




۴۵
Backing up/restoring a mySQL
                        database
• You can back up an entire database with a command such as
         mysqldump –h mysql –u martin martin > backup.sql



  (Run from the Unix command line )line.)
• This gives a script containing SQL commands to reconstruct the
  table structure (of all tables) and all of the data in the table(s).
                   (            )                                 ()
• To restore the database (from scratch) you can use this type of
  Unix command:
            mysql –h mysql –u martin martin < backup sql
                       h             u                       backup.sql
    (Use with caution, as this can overwrite your database.)
• Other commands are possible to backup/restore only certain
  tables or items in tables etc if that is what you desire For
                     tables, etc.                   desire.
  example
    mysqldump –h mysql –u martin martin books clients> backup.sql

stores information about the “books” and “clients” tables in the
                              books       clients
   “martin” database.
   ۴۶
Putting Content into Your Database
                       with PHP
We can simply use PHP functions and mySQL queries together:

• Connect to the database server and login (this is the PHP command to do so)
    mysql_connect("host","username","password");
                                                                            Host:        mysql

• Choose the database                                                       Database:          martin

          mysql_select_db("database");                                      Username:          martin
                                                                            Password:          <blank>

      • Send SQL queries to the server to add, delete, and modify data
         mysql_query("query"); (use the exact same query string as you would
                                             normally use in SQL, without the trailing semi‐colon)

• Close the connection to the database server (to ensure the information is stored properly)
   mysql_close();

• Note: For this to work properly on the UoL server, you must access the PHP script through the cgi server
(http://cgi.csc.liv.ac.uk/~martin/getstuff.php for example).
       ۴٧
Student Database: data_in.php
<html>
<head>
<title>Putting Data in the DB</title>
</head>
<body>
<?php
/*insert students into DB*/
if(isset($_POST["submit"])) {

      $db = mysql_connect("mysql”, ”martin");
      mysql_select_db("martin");

      $date=date("Y-m-d");
      $d t d t ("Y    d")     /*   G t th current date in the right SQL f
                                   Get the      t d t i th     i ht     format
                                                                             t   */

      $sql="INSERT INTO students VALUES(NULL,'“ . $_POST[“f_name"] . "','“ .
      $_POST["l_name"] . "',“ . $_POST["student_id"] . ",'“ . $_POST["email"] .
      "','“ . $date . "',“ . $_POST["gr"] . ")";      /* construct the query
      */

      mysql_query($sql);     /*    execute the query   */
      mysql_close();

      echo"<h3>Thank you. The data has been entered.</h3> n";

      echo'<p><a href="data_in.php">Back to registration</a></p>‘ . “n”;

      echo'<p><a href "data out php">View the student lists</a></p>‘ .”n”;
                 href="data_out.php">View                             ”n”;

      }
 ۴٨
Student Database: data_in.php
                              _ p p
else {
?>
<h3>Enter your items into the database</h3>
<form action="data_in.php" method="POST">
First Name: <input type="text" name=“f_name“ /> <br/>
Last Name: <input type="text" name=“l_name“ /> <br/>
              p     yp
ID: <input type="text" name=“student_id“ /> <br/>
email: <input type="text" name=“email“ /> <br/>
Group: <select name="gr">
       <option value ="1">1</option>
         p                    p
       <option value ="2">2</option>
       <option value ="3">3</option>
</select><br/><br/>
<input type="submit" name="submit“ /> <input type="reset“ />
   p    yp                               p    yp
</form>

<?php
   }
?>

</body>
</html>


 ۴٩
Getting Content out of Your Database
                     with PHP
                       ith
Similarly,
Similarly we can get some information from a database:

• Connect to the server and login, choose a database
    mysql_connect("host","username","password");
        l       t("h t" "         ""        d")
 mysql_select_db("database");

      • S d an SQL query t th server t select d t from th d t b
        Send             to the      to l t data f     the database into an array
                                                                    i t
          $result=mysql_query("query");
      • Either, look into a row and a fieldname
              ,
       $num=mysql_numrows($result);
         $variable=mysql_result($result,$i,"fieldname");
            • Or, fetch rows one by one
          $row=mysql_fetch_array($result);

• Close the connection to the database server
   mysql_close();
    ۵٠
Student Database: data_out.php
<html>
<head>
<title>Getting Data out of the DB</title>
</head>
<body>
<h1> Student Database </h1>
<p> Order the full list of students by
<a href="data_out.php?order=date">date</a>,
<href="data_out.php?order=student_id">id</a>, or
by <a href="data_out.php?order=l_name">surname</a>.
</p>

<p>
<form action="data_out.php" method="POST">
Or only see the list of students in group
<select name="gr">
 <option value ="1">1</option>
 <option value ="2">2</option>
 <option value ="3">3</option>
</select>
<br/>
<input type="submit" name="submit“ />
</form>
</p>


  ۵١
Student Database: data_out.php
<?php
  p p
/*get students from the DB */
$db = mysql_connect("mysql",“martin");
mysql_select_db(“martin", $db);

switch($_GET["order"]){
case 'date': $sql = "SELECT * FROM students ORDER BY date"; break;
case ‘student_id': $sql = "SELECT * FROM students ORDER BY student_id"; break;
case ‘l_name': $sql = "SELECT * FROM students ORDER BY l_name"; break;

default: $sql = “SELECT * FROM students”; break;
}
if(isset($_POST["submit"])){
  $sql = “SELECT * FROM students WHERE gr=“ . $_POST["gr"];
}

$result=mysql_query($sql); /* execute the query */
while($row=mysql_fetch_array($result)){
  echo "<h4> Name: “ . $row["l_name"] . ', ‘ . $row["f_name"] . "</h4> n";
  echo "<h5> ID: “ . $row[“student_id"] . "<br/> Email: “ . $row["email"] . "<br/> Group: “ . $row["gr"] . "<br/> Posted:
     “ . $row["date"] . "</h5> n";
}
mysql_close();
?>
</body>
</html>

   ۵٢
Can Do Even More with PHP

•   Can create tables in PHP
•   Can delete
    C d l t rows and columns
                        d l
•   Can make updates
•   Can make queries to several tables
•   Can get connected to several databases


             * Find more iinformation on PHP/ SQL
               Fi d         f    ti      PHP/mySQL




    ۵٣
Learning Outcomes

In these last lectures you have learned
  What is SQL
  How to access mySQL database
  How to create a basic mySQL database
  How to use some basic queries
  How t
  H to use PHP and mySQL
                     d SQL




 ۵۴
Using several tables

• mySQL (like any other database system that uses SQL) is a relational
  database, meaning that it’s designed to work with multiple tables, and it
  allows you to make queries that involve several tables
                                                     tables.
• Using multiple tables allows us to store lots of information without much
  duplication.
  duplication
• Allows for easier updating (both insertion and deletion).
• We can also perform different types of queries, combining the
                                          queries
  information in different ways depending upon our needs.




۵۵
Advanced queries
•   Suppose that we have defined several tables as follows:
      pp
    mysql> describe clients;
    +-----------+-------------+------+-----+---------+----------------+
    | Field     | Type        | Null | Key | Default | Extra          |
    +-----------+-------------+------+-----+---------+----------------+
    | client_id | int(11)     | NO   | PRI | NULL    | auto_increment |
    | f_name    | varchar(20) | YES |      | NULL    |                |
    | l_name    | varchar(30) | NO   |     |         |                |
    | address
       dd       | varchar(40) | YES |
                      h (40)               | NULL    |                |
    | city      | varchar(30) | YES |      | NULL    |                |
    | postcode | varchar(12) | YES |       | NULL    |                |
    +-----------+-------------+------+-----+---------+----------------+
    6 rows i set (0 01 sec)
           in   t (0.01    )

   mysql> describe purchases;
   +-------------+---------+------+-----+---------+----------------+
   | Fi ld
     Field       | T
                   Type    | N ll | K
                              Null   Key | D f lt | Extra
                                           Default   E t            |
   +-------------+---------+------+-----+---------+----------------+
   | purchase_id | int(11) | NO    | PRI | NULL    | auto_increment |
   | client_id   | int(11) | NO    |     |         |                |
   | d t
     date        | d t
                   date    | NO    |     |         |                |
   +-------------+---------+------+-----+---------+----------------+
۵۶
   3 rows in set (0.00 sec)
mysql> describe itemlist;
+-------------+---------+------+-----+---------+----------------+
| Field       | T pe
                Type    | N ll | Ke | Defa lt | E t a
                          Null   Key   Default   Extra          |
+-------------+---------+------+-----+---------+----------------+
| item_id     | int(11) | NO   | PRI | NULL    | auto_increment |
| purchase_id | int(11) | NO   |     |         |                |
| book id
  book_id     | int(11) | NO   |     |         |                |
+-------------+---------+------+-----+---------+----------------+
3 rows in set (0.00 sec)

mysql> describe books;
+---------+-------------+------+-----+---------+----------------+
| Field   | Type        | Null | Key | Default | Extra          |
+---------+-------------+------+-----+---------+----------------+
| book id | int(11)
  book_id               | NO   | PRI | NULL    | auto_increment |
                                                 auto increment
| title   | varchar(50) | NO   |     |         |                |
| pages   | int(11)     | YES |      | NULL    |                |
+---------+-------------+------+-----+---------+----------------+
3 rows in set (0.00 sec)
              (0 00

mysql>




  ۵٧
The idea here is that clients can make multiple purchases. Each
  purchase will be assigned a unique id, but can consist of multiple
  items. Each item is a book, which can be purchased by many
  different people
            people.

Defining the tables in this fashion allows us to avoid (
       g                                               (excessive))
  repetition of information, and lets us query the data in different
  fashions.

The “id” fields are the keys that we use to tie the various tables together,
  namely a customer (or client) with “client id” will make several
                                        client_id
  purchases. We can identify their purchases by searching for
  matches of the client_id in the purchases table.

Similarly, we can find the actual items that comprise a particular
   purchase by searching for the purchase id key in the itemlist table
                                    purchase_id                    table.
۵٨
Populate the tables
•   Suppose that we have this data in the tables:

mysql> select * from clients;
+-----------+---------+--------+--------------------------+----------------+----------+
| client_id | f_name | l_name | address                   | city           | postcode |
+-----------+---------+--------+--------------------------+----------------+----------+
|         1 | Russell | Martin | Dept of Computer Science | Liverpool
                                   p        p                    p         | L69 3BX |
|         2 | Bob     | Milnor | 12 Peachtree Ln          | Liverpool      | L12 3DX |
|         3 | Sarah   | Ford   | 542b Jersey Rd           | West Kirby     | L43 8JK |
|         4 | Larry   | Vance | 76 Jarhead Ln             | Liverpool      | L12 4RT |
|         5 | Paul    | Abbott | 90 Crabtree Pl           | Leamingotn Spa | CV32 7YP |
+-----------+---------+--------+--------------------------+----------------+----------+
5 rows in set (0.01 sec)

mysql> select * from books;
+---------+---------------------+-------+
| book_id | title               | pages |
+---------+---------------------+-------+
|       1 | Linux in a Nutshell |   120 |
|       2 | Learning SQL        |   289 |
|                      g
        3 | Abstract Algebra    |   320 |
|       4 | Rising Sun          |   830 |
|       5 | Round the Moon      |   136 |
|       6 | Blackbeard          |   292 |
+---------+---------------------+-------+
6 rows in set (0.00 sec)
              (0 00

mysql>
۵٩
mysql> SELECT * FROM purchases;
+-------------+-----------+------------+
| purchase_id | client_id | date        |
+-------------+-----------+------------+
|           1 |         1 | 2007-11-09 |
|           2 |         1 | 2007-11-10 |
|           4 |         2 | 2007-11-20 |
|           5 |         4 | 2007-11-20 |
|           6 |          3 | 2007 11 21 |
                             2007-11-21
|           7 |         5 | 2007-11-25 |
|           8 |         3 | 2007-11-25 |
+-------------+-----------+------------+
7 rows in set (0.00 sec)

mysql> SELECT * FROM itemlist;
+---------+-------------+---------+
| item_id | purchase_id | book_id |
+---------+-------------+---------+
|       1 |           1 |       2 |
|       2 |           1 |       6 |
|       3 |           1 |       3 |
|       4 |           2 |       4 |
|       5 |           2 |       5 |
|       6 |           4 |       5 |
|       7 |           4 |       6 |
|       8 |           5 |       1 |
|       9 |           5 |       3 |
|      10 |           6 |       5 |
|      11 |           7 |       2 |
|      12 |           8 |       3 |
+---------+-------------+---------+
12 rows in set (0.00 sec)

mysql>
۶٠
Advanced Queries
•    We can link these tables together by queries of this type:

myql> SELECT * from clients, purchases WHERE clients.client_id=purchases.client_id ORDER BY purchase_id;
+----------+---------+--------+--------------------------+----------------+----------+-------------+-----------+------------+
|client_id | f_name | l_name | address                               | city           | postcode | purchase_id | client_id | date          |
-----------+---------+--------+--------------------------+----------------+----------+-------------+-----------+------------+
|       1 | Russell | Martin | Dept of Computer Science | Liverpool                   | L69 3BX          |        1|         1 | 2007-11-09 |
|       1 | Russell | Martin | Dept of Computer Science | Liverpool                   | L69 3BX          |        2|         1 | 2007 11 10 |
                                                                                                                                 2007-11-10
|       2 | Bob | Milnor | 12 Peachtree Ln                          | Liverpool        | L12 3DX          |       4|        2 | 2007-11-20 |
|       4 | Larry | Vance | 76 Jarhead Ln                           | Liverpool        | L12 4RT         |        5|         4 | 2007-11-20 |
|       3 | Sarah | Ford | 542b Jersey Rd                           | West Kirby | L43 8JK               |         6|        3 | 2007-11-21 |
|       5 | Paul | Abbott | 90 Crabtree Pl                         | Leamingotn Spa | CV32 7YP |                  7|         5 | 2007-11-25 |
|       3 | Sarah | Ford | 542b Jersey Rd                          | West Kirby         | L43 8JK        |         8|        3 | 2007-11-25 |
+-----------+---------+--------+--------------------------+----------------+----------+-------------+-----------+------------+
7 rows in set (0 01 sec)
                 (0.01

mysql>

    So you can see that this query gives us all of the purchase orders
    that have been placed by the clients (but not the number of items, or the items
      ۶١
    themselves).
•    You can see that the “client_id” field is repeated. This is because we selected all columns
     (
     (using the * option) in both tables, and it appears in each table.
          g        p )                            pp

•    To avoid this repeated information, we can make a query like:

mysql> SELECT clients.client_id, f_name, l_name, address, city, postcode, purchases.purchase_id,date from
      clients, purchases WHERE clients.client_id=purchases.client_id ORDER BY purchase_id;
+-----------+---------+--------+--------------------------+----------------+----------+-------------+------------+
| client_id | f_name | l_name | address
  ce d            a e         a e add ess                     | city
                                                                c y          | postcode | purchase id | date
                                                                               pos code pu c ase_ d da e                 |
+-----------+---------+--------+--------------------------+----------------+----------+-------------+------------+
|       1 | Russell | Martin | Dept of Computer Science | Liverpool | L69 3BX                            |         1 | 2007-11-09 |
|       1 | Russell | Martin | Dept of Computer Science | Liverpool | L69 3BX                            |         2 | 2007-11-10 |
|       2 | B b | Milnor | 12 P ht Ln
            Bob       Mil          Peachtree L                      | Liverpooll | L12 3DX
                                                                      Li                                 |         4 | 2007 11 20 |
                                                                                                                       2007-11-20
|       4 | Larry | Vance | 76 Jarhead Ln                           | Liverpool | L12 4RT                |         5 | 2007-11-20 |
|       3 | Sarah | Ford | 542b Jersey Rd                           | West Kirby | L43 8JK                |        6 | 2007-11-21 |
|       5 | Paul | Abbott | 90 Crabtree Pl                         | Leamingotn Spa | CV32 7YP |
                                                                              g       p                            7 | 2007-11-25 |
|       3 | Sarah | Ford | 542b Jersey Rd                          | West Kirby | L43 8JK                 |        8 | 2007-11-25 |
+-----------+---------+--------+--------------------------+----------------+----------+-------------+------------+
7 rows in set (0.00 sec)

mysql>

The “NATURAL JOIN” option can obtain the same result as above, as they share a single key.
     NATURAL JOIN

mysql> SELECT * FROM clients NATURAL JOIN purchases;
۶٢
• We need not select all columns:

mysql> SELECT f_name,l_name, purchases.purchase_id FROM
   clients NATURAL JOIN purchases ORDER BY purchase_id;
+---------+---------+-------------+
| f_name | l_name | purchase_id |
+---------+---------+-------------+
| Russell | Martin |            1 |
| Russell | Martin |            2 |
| Bob      | Milnor |           4 |
| Larry    | Vance   |          5 |
| Sarah    | Ford    |          6 |
| Paul     | Abbott |           7 |
| Sarah    | Ford    |          8 |
+---------+----------+-------------+
7 rows i set (0 00 sec)
        in   t (0.00   )

mysql>


۶٣
More Complex Queries
•    We can create most any type of query that you might think of with a (more
     complicated) “WHERE” clause:

mysql> SELECT purchases.purchase_id, f_name, l_name, date
   FROM purchases, clients WHERE
   purchases.client_id=clients.client_id;
+-------------+---------+--------+------------+
+             +          +        +            +
| purchase_id | f_name | l_name | date         |
+-------------+---------+--------+------------+
|           1 | Russell | Martin | 2007 11 09 |
                                    2007-11-09
|           2 | Russell | Martin | 2007-11-10 |
|           4 | Bob      | Milnor | 2007-11-20 |
|           5 | Larry    | Vance | 2007-11-20 |
                                    2007 11 20
|           6 | Sarah    | Ford   | 2007-11-21 |
|           7 | Paul     | Abbott | 2007-11-25 |
|           8 | Sarah    | Ford   | 2007-11-25 |
                                    2007 11 25
+-------------+---------+--------+------------+
7 rows in set (0.00 sec)

mysql>
۶۴
More Complex Queries (cont )
                                  (cont.)
• Find the purchases by the person named “Ford”
                                         “Ford”.

mysql> SELECT purchases.purchase_id, f_name, l_name, date
   FROM purchases, clients
       WHERE (purchases.client_id=clients.client_id) AND
   (l_name='Ford');
+-------------+--------+--------+------------+
+             +        +        +            +
| purchase_id | f_name | l_name | date       |
+-------------+--------+--------+------------+
|           6 | Sarah | Ford    | 2007-11-21 |
                                  2007 11 21
|           8 | Sarah | Ford    | 2007-11-25 |
+-------------+--------+--------+------------+
2 rows in set (0.01 sec)

mysql>


۶۵
Querying multiple tables
• In addition, we can query many tables (i.e. more than two) at once:
• First we’ll find all the purchases by a person with ll_name= Martin .
        we ll                                            name=‘Martin’

mysql> select p
 y q          purchases.purchase_id, f_name, l_name, date FROM
                         p         ,       ,       ,
   purchases, clients WHERE
   (purchases.client_id=clients.client_id) AND (l_name='Martin')
   ORDER BY purchases.purchase_id;
+-------------+---------+--------+------------+
| purchase_id | f_name | l_name | date        |
+-------------+---------+--------+------------+
|           1 | Russell | Martin | 2007-11-09 |
|           2 | Russell | Martin | 2007-11-10 |
+-------------+---------+--------+------------+
2 rows in set (0.00 sec)

mysql>


۶۶
Querying multiple tables (cont.)
• Now let’s find out the items (the “book_id”) in each purchase:

mysql> SELECT purchases.purchase_id, f
    l>            h         h    id f_name, ll_name, d t
                                                      date,
   itemlist.book_id FROM purchases, clients, itemlist
       WHERE (purchases.client_id=clients.client_id) AND
   (l_name='Martin') AND
   (purchases.purchase_id=itemlist.purchase_id)
   (purchases purchase id=itemlist purchase id)
       ORDER BY purchases.purchase_id;
+-------------+---------+--------+------------+---------+
| purchase_id | f_name | l_name | date        | book_id |
+-------------+---------+--------+------------+---------+
|           1 | Russell | Martin | 2007-11-09 |        2 |
|           1 | Russell | Martin | 2007-11-09 |        6 |
|           1 | Russell | Martin | 2007-11-09 |        3 |
|           2 | Russell | Martin | 2007-11-10 |        5 |
|           2 | Russell | Martin | 2007-11-10 |        4 |
+-------------+---------+--------+------------+---------+

5 rows in set (0.00 sec)

mysql>

۶٧
Querying multiple tables (cont.)
• Finally we can find the actual book titles by querying all four tables at
  once:
mysql> SELECT purchases.purchase_id, f_name, l_name, date,
   itemlist.book_id, title
         FROM purchases clients itemlist, books
              purchases, clients, itemlist
         WHERE (purchases.client_id=clients.client_id) AND
   (l_name='Martin') AND
   (purchases.purchase_id=itemlist.purchase_id) AND
   (itemlist.book_id books.book_id)
   (itemlist book id=books book id)
         ORDER BY purchases.purchase_id;
+-------------+---------+--------+------------+---------+------------------+
| purchase_id | f_name | l_name | date        | book_id | title            |
+-------------+---------+--------+------------+---------+------------------+
|           1 | Russell | Martin | 2007-11-09 |       6 | Blackbeard       |
|           1 | Russell | Martin | 2007-11-09 |       2 | Learning SQL     |
|           1 | Russell | Martin | 2007-11-09 |       3 | Abstract Algebra |
|           2 | Russell | Martin | 2007-11-10 |       4 | Rising Sun       |
|           2 | Russell | Martin | 2007-11-10 |
                                   2007 11 10         5 | Round the Moon   |
+-------------+---------+--------+------------+---------+------------------+
5 rows in set (0.00 sec)

mysql>


۶٨
Querying multiple tables (cont.)
• As before, we need not select all of the columns:
mysql> SELECT purchases.purchase_id, title
       FROM purchases, clients, itemlist, books
       WHERE (purchases client id=clients client id) AND
             (purchases.client_id=clients.client_id)
   (l_name='Martin') AND
   (purchases.purchase_id=itemlist.purchase_id) AND
   (itemlist.book_id=books.book_id)
       ORDER BY purchases.purchase id;
                purchases.purchase_id;
+-------------+------------------+
| purchase_id | title            |
+-------------+------------------+
|           1 | Blackbeard       |
|           1 | Learning SQL     |
|           1 | Abstract Algebra |
|           2 | Rising Sun       |
|           2 | Round the Moon   |
+-------------+------------------+
5 rows in set (0.00 sec)

mysql>
۶٩
Using aliases in queries
• Especially long queries might benefit from the SQL capability for
  using aliases.
mysql> select p.purchase_id, title FROM purchases AS p, clients
   AS c, itemlist AS i, books WHERE (p.client_id=c.client_id) AND
   (l_name='Martin') AND (p.purchase_id=i.purchase_id) AND
   (i.book_id books.book_id)
   (i.book id=books.book id) ORDER BY p.purchase id;
                                      p.purchase_id;
+-------------+------------------+
| purchase_id | title            |
+-------------+------------------+
|           1 | Blackbeard       |
|           1 | Learning SQL     |
|           1 | Abstract Algebra |
|           2 | Rising Sun       |
|           2 | Round the Moon   |
+-------------+------------------+
5 rows in set (0.00 sec)

An alias uses the SQL keyword ‘AS’ to associate a new identifier with a
   table. It should appear after the table name and before the alias.
   Once a table is aliased you must use that alias everywhere iin th
   O        t bl i li d             t     th t li        h        the
٧٠
   SQL query.
Searching tables
The SQL “wildcard” character is the % symbol That is it can literally represent
         wildcard                     symbol.        is,
   anything. Using it we can build searches like the following:
mysql> SELECT * FROM clients WHERE l_name LIKE '%a%';
+-----------+---------+--------+--------------------------+----------------+----------+
+           +         +        +                          +                +          +
| client_id | f_name | l_name | address                   | city           | postcode |
+-----------+---------+--------+--------------------------+----------------+----------+
|         1 | Russell | Martin | Dept of Computer Science | Liverpool      | L69 3BX |
|         4 | Larry   | Vance | 76 Jarhead Ln             | Liverpool      | L12 4RT |
|         5 | Paul    | Abbott | 90 Crabtree Pl           | Leamingotn Spa | CV32 7YP |
+-----------+---------+--------+--------------------------+----------------+----------+
3 rows in set (0.00 sec)


This above search finds all data that has a letter “a” in the user_id column.
mysql> SELECT * FROM clients where l_name LIKE '%an%';
+-----------+--------+--------+---------------+-----------+----------+
| client_id | f_name | l_name | address       | city      | postcode |
+-----------+--------+--------+---------------+-----------+----------+
|         4 | Larry | Vance | 76 Jarhead Ln | Liverpool | L12 4RT |
+-----------+--------+--------+---------------+-----------+----------+
1 row in set (0.00 sec)




 ٧١
Searching tables (cont.)
mysql> SELECT clients.client_id, f_name, l_name FROM clients NATURAL JOIN
   purchases where l_name LIKE '%a%';
+-----------+---------+--------+
| client_id | f_name | l_name |
+-----------+---------+--------+
|         1 | Russell | Martin |
|         1 | Russell | Martin |
|         4 | Larry   | Vance |
|         5 | Paul    | Abbott |
+-----------+---------+--------+
4 rows in set (0.00 sec)


mysql> SELECT clients client id f name l name FROM clients purchases WHERE
                clients.client_id, f_name, l_name      clients,
     (l_name LIKE '%a%') AND (clients.client_id=purchases.client_id)
     AND (clients.client_id > 1);
+-----------+--------+--------+
| client_id | f_name | l_name |
+-----------+--------+--------+
|           4 | Larry | Vance |
|           5 | Paul   | Abbott |
+-----------+--------+--------+
2 ٧٢
   rows in set (0.00 sec)
More on PHP and SQL
To increase security of your PHP/SQL setup (and to make it easier to change the
    database you use), it’s recommended that you build an “include” file that will have
                  use) it s                                include
    the information you use to connect to the database.

<?php
/* Save this as db_login.php (or whatever you like) and include it
in your php script. */

// Here’s the information to connect to the database.
$db_host = ‘mysql’;
$db_database=‘martin’;
$db_username= martin ;
$db username=‘martin’;
$db_password=‘’;
?>


If someone tries to view this file through their browser, the PHP interpreter will process
     it and return a blank page to the user (there’s no HTML in the file).


٧٣
Connecting to the database
                             g
Now you can build your PHP script as follows (using the commands that we discussed
   previously):

<?php
require_once (‘db_login.php’);

$connection = mysql_connect($db_host, $db_username, $db_password);

if (!$connection)    /* check if the connection was actually successful             */
    {
      exit(“Could not connect to the database: <br/>” .
         htmlspecialchars(mysql_error()) );
    }
else {
   // more statements here. . .
       }
?>


Note: The function ‘htmlspecialchars()’ converts special characters in a string into their
   HTML escape sequences (like ‘&’ into ‘&amp;’ and so forth).
   This can also be used to increase the security of your code by and help thwart attacks
   on your database by passing it information that your client has submitted before trying
٧۴ to insert it in your database.
MySQL queries inside of PHP
Your mySQL queries from a PHP script are the same as they are as when you’re using the
   mySQL program from the command line with one difference… the queries do not have
   a semi-colon at the end.
Aside f
A id from this difference, all of the regular SQL commands and k
          thi diff          ll f th       l             d    d keywords are available
                                                                     d         il bl
   when you perform your queries.

You
Y can create new t bl alter, and d l t th from inside of a PHP script, and you can
             t       tables, lt        d delete them f    i id f                 i t d
   also insert and delete rows of tables as normal too. For any such operation, you’ll
   likely want to check to see if it’s successful (especially if you’re trying to insert into or
   extract data from the database).

<?php
// Assuming a valid database connection has been established.
// Build the query string by assigning variables...
$query = $select . $column . $from . $tables . $where;
$result = mysql_query($query);
if(!$result) {
    exit(“Could not query the database: <br/>” .
                                           /
                          htmlspecialchars(mysql_error()) );
             }
else    {
    // process the data
        }
?>
 ٧۵
Processing the results of a query

•    There
     Th are two main PHP methods to f h the results of an SQL query, these b i
                     i           h d     fetch h    l f               h    being
     ‘mysql_fetch_row()’ and ‘mysql_fetch_array()’.

<?php
// Assuming a database connection, and a valid query string.
$result = mysql_query( $query );
while ($result_row = mysql_fetch_row($result)) {
    echo $result_row[2] . ‘<br/>’;
  }

?>


The ‘mysql fetch row()’ command fetches the query results as an enumerated array
     mysql_fetch_row()
   (an array that uses numerical indices), one row at a time, returning FALSE when
   there are no more rows (ending the ‘while’ loop in this case).

٧۶
Processing the results of a query (cont.)
•    mysql_fetch_array can get a row of results as an associative array (using
     strings as the array indices) It takes a result as its first parameter and an optional
                          indices).                               parameter,
     second parameter as a way to bind the results in the array.
•    If MYSQL_ASSOC is specified, the results are indexed using the column names in
     the query. If MYSQL_NUM is specified, then the numerical array indices (starting
          query MYSQL NUM specified
     at zero) access the results. The default value MYSQL_BOTH returns an array with
     both types.
while ( $row = mysql_fetch_array($result, MYSQL_ASSOC) ) {
     echo $row[“title”] . ‘<br/>’;
   }


•    Using a statement like ‘mysql_fetch_array($result, MYSQL_NUM)’ is essentially
     equivalent to the statement ‘mysql_fetch_row($result)’ as they both return arrays
     stored with numerical indices
                            indices.
•    The ‘mysql_fetch_array()’ command can be used to save memory by specifying,
     say, MYSQL_ASSOC, instead of the default value.

٧٧
Other useful PHP/SQL related functions

•    The f
     Th function ‘mysql_data_seek($result, $ l )’ can b used to move the iinternall
               i ‘        l d         k($     l $value)’     be     d             h
     result pointer (which is advanced automatically when commands like
     ‘mysql_fetch_array()’ is called). This allows you, for example, to reprocess the
     results of a query (without having to access the database again).
     ‘mysql_data_seek($result, 0);’ will reset the pointer to the initial row in the query
     result (but is an error if the query result was empty).
            (                       q y                p y)

•    ‘mysql_num_rows ($result);’ returns the number of rows in the query result.

•    ‘mysql_affected_rows();’ gives the number of affected rows by the last INSERT,
     DELETE, UPDATE
     DELETE UPDATE, or REPLACE query.  query

•    ‘mysql_insert_id();’ returns the ID generated by the AUTO_INCREMENT of the
     most recent query if there was one, or ‘0’ if there was no AUTO_INCREMENT
٧٨   value.

More Related Content

What's hot (20)

Introduction to php basics
Introduction to php   basicsIntroduction to php   basics
Introduction to php basics
 
PHP
PHPPHP
PHP
 
Php a dynamic web scripting language
Php   a dynamic web scripting languagePhp   a dynamic web scripting language
Php a dynamic web scripting language
 
Hacking with hhvm
Hacking with hhvmHacking with hhvm
Hacking with hhvm
 
Php’s guts
Php’s gutsPhp’s guts
Php’s guts
 
Php basics
Php basicsPhp basics
Php basics
 
Introduction To PHP
Introduction To PHPIntroduction To PHP
Introduction To PHP
 
PHP FUNCTIONS
PHP FUNCTIONSPHP FUNCTIONS
PHP FUNCTIONS
 
PHP - Introduction to PHP
PHP -  Introduction to PHPPHP -  Introduction to PHP
PHP - Introduction to PHP
 
PHP - Introduction to PHP Functions
PHP -  Introduction to PHP FunctionsPHP -  Introduction to PHP Functions
PHP - Introduction to PHP Functions
 
Basics PHP
Basics PHPBasics PHP
Basics PHP
 
Overview of PHP and MYSQL
Overview of PHP and MYSQLOverview of PHP and MYSQL
Overview of PHP and MYSQL
 
Php.ppt
Php.pptPhp.ppt
Php.ppt
 
PHP - Introduction to PHP Date and Time Functions
PHP -  Introduction to  PHP Date and Time FunctionsPHP -  Introduction to  PHP Date and Time Functions
PHP - Introduction to PHP Date and Time Functions
 
Day1
Day1Day1
Day1
 
Php(report)
Php(report)Php(report)
Php(report)
 
Control Structures In Php 2
Control Structures In Php 2Control Structures In Php 2
Control Structures In Php 2
 
Php tutorial(w3schools)
Php tutorial(w3schools)Php tutorial(w3schools)
Php tutorial(w3schools)
 
Php tutorial
Php  tutorialPhp  tutorial
Php tutorial
 
PHP slides
PHP slidesPHP slides
PHP slides
 

Similar to Lecture8

Similar to Lecture8 (20)

WT_PHP_PART1.pdf
WT_PHP_PART1.pdfWT_PHP_PART1.pdf
WT_PHP_PART1.pdf
 
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
 
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
 
Php i basic chapter 3
Php i basic chapter 3Php i basic chapter 3
Php i basic chapter 3
 
Php Tutorial
Php TutorialPhp Tutorial
Php Tutorial
 
php 1
php 1php 1
php 1
 
php basics
php basicsphp basics
php basics
 
basic concept of php(Gunikhan sonowal)
basic concept of php(Gunikhan sonowal)basic concept of php(Gunikhan sonowal)
basic concept of php(Gunikhan sonowal)
 
PHP
PHPPHP
PHP
 
PHP Introduction and Training Material
PHP Introduction and Training MaterialPHP Introduction and Training Material
PHP Introduction and Training Material
 
Php
PhpPhp
Php
 
PHP from soup to nuts Course Deck
PHP from soup to nuts Course DeckPHP from soup to nuts Course Deck
PHP from soup to nuts Course Deck
 
Php unit i
Php unit iPhp unit i
Php unit i
 
Ppt php
Ppt phpPpt php
Ppt php
 
Php converted pdf
Php converted pdfPhp converted pdf
Php converted pdf
 
php app development 1
php app development 1php app development 1
php app development 1
 
Php mysql ppt
Php mysql pptPhp mysql ppt
Php mysql ppt
 
Php introduction
Php introductionPhp introduction
Php introduction
 
FYBSC IT Web Programming Unit IV PHP and MySQL
FYBSC IT Web Programming Unit IV  PHP and MySQLFYBSC IT Web Programming Unit IV  PHP and MySQL
FYBSC IT Web Programming Unit IV PHP and MySQL
 
Php
PhpPhp
Php
 

More from Majid Taghiloo (6)

Lecture7
Lecture7Lecture7
Lecture7
 
Lecture6
Lecture6Lecture6
Lecture6
 
Lecture5
Lecture5Lecture5
Lecture5
 
Lecture3
Lecture3Lecture3
Lecture3
 
Lecture2
Lecture2Lecture2
Lecture2
 
Lecture1
Lecture1Lecture1
Lecture1
 

Lecture8

  • 1. PHP IT1 Course Slide Instructor: Majid Taghiloo ١
  • 2. Server-Side Dynamic Web Programming • CGI is one of the most common approaches to server-side programming Universal support: (almost) Every server supports CGI programming. A great deal of ready-to-use CGI code. Most APIs (Application Programming Interfaces) also allow CGI p g ( pp g g ) programming.g Choice of languages: CGI is extremely general, so that programs may be written in nearly any language. Perl is by far the most popular, with the result that many people think that CGI means Perl. But C, C++, Ruby, and Python are also used for CGI programming. Drawbacks: A separate process is run every time the script is requested. A distinction is made between HTML pages and code. • Other server-side alternatives try to avoid the drawbacks Server-Side Includes (SSI): Code is embedded in HTML pages, and evaluated on the server while the pages are being served. Add dynamically generated content to an existing HTML page, without having to serve the entire page via a CGI program program. Active Server Pages (ASP, Microsoft) : The ASP engine is integrated into the web server so it does not require an additional process. It allows programmers to mix code within HTML pages instead of writing separate programs. (Drawback(?) Must be run on a server using Microsoft server software.) programs software ) Java Servlets (Sun): As CGI scripts, they are code that creates documents. These must be compiled as classes which are dynamically loaded by the web server when they are run. Java Server Pages ( g (JSP): Like ASP, another technology that allows developers to embed Java in ) , gy p web pages. ٢
  • 3. PHP • developed in 1995 by Rasmus Lerdorf (member of the Apache Group) originally designed as a tool for tracking visitors at Lerdorf's Web site within 2 years, widely used in co ju c o with the Apache se e yea s, de y conjunction e pac e server developed into full-featured, scripting language for server-side programming free, open-source server plug-ins exist for various servers plug ins now fully integrated to work with mySQL databases • PHP is similar to JavaScript, only it’s a server-side l i i il t J S i t l it’ id language PHP code is embedded in HTML using tags when a page request arrives, the server recognizes PHP content via the file extension (.php or .phtml) the server executes the PHP code, substitutes output into the HTML page the resulting page is then downloaded to the client user never sees the PHP code, only the output in the page • The acronym PHP means (in a slightly recursive definition) PHP: Hypertext Preprocessor ٣
  • 4. What do You Need? • Our server supports PHP O PHP – You don't need to do anything special! * – You don't need to compile anything or install any extra tools! – Create some .php f l in your web d h files b directory ‐ and the server will parse them f d h ll h for you. * Slightly different rules apply when dealing with an SQL database (as will be explained when we get to that point). • Most servers support PHP – Download PHP for free here: http://www.php.net/downloads.php – Download MySQL for free here: http://www mysql com/downloads/index html http://www.mysql.com/downloads/index.html – Download Apache for free here: http://httpd.apache.org/download.cgi (Note: All of this is already present on the CS servers, so you need not do any installation yourself to utilize PHP on our machines.) ۴
  • 5. Help with PHP Loads of information, including help on individual PHP functions may be found at http://uk.php.net/ h // k h / ۵
  • 6. Basic PHP syntax A PHP scripting block always starts with <?php and ends with ?> A PHP scripting block ?>. can be placed (almost) anywhere in an HTML document. <html> <!‐‐ hello.php COMP519 ‐‐> print and echo i t h <head><title>Hello World</title></head> <body> for output <p>This is going to be ignored by the PHP interpreter.</p> <?php echo ‘<p>While this is going to be parsed.</p>‘; ?> a semicolon (;) at the <p>This will also be ignored by PHP.</p> end of each statement <?php i t(‘< >H ll <? h print(‘<p>Hello and welcome t <i> </i> page!</p>'); d l to <i>my</i> !</ >') ?> <?php //This is a comment // for a single-line comment single line /* /* and */ for a large This is a comment comment block. block */ ?> </body> </html> ۶ The server executes the print and echo statements, substitutes output.
  • 7. Scalars All variables in PHP start with a $ sign symbol. A variable's type is determined by the $ g y yp y context in which that variable is used (i.e. there is no strong‐typing in PHP). <html><head></head> <!‐‐ scalars.php <! scalars php COMP519 ‐‐> > <body> <p> <?php $foo = true; if ($foo) echo "It is TRUE! <br /> n"; $txt='1234'; echo "$txt <br /> n"; Four scalar types: $a = 1234; echo "$a <br /> n"; boolean b l $a = ‐123; echo "$a <br /> n"; true or false $a = 1.234; echo "$a <br /> n"; $a br / n ; integer, $a = 1.2e3; float, echo "$a <br /> n"; $a = 7E‐10; floating point numbers echo "$a <br /> n"; echo 'Arnold once said: "I'll be back , "<br /> n"; Arnold I ll back"' <br n ; stringg $beer = 'Heineken'; single quoted echo "$beer's taste is great <br /> n"; $str = <<<EOD double quoted Example of string spanning multiple lines using “heredoc” syntax. EOD; echo $str; ?> </p> </body> </html> ٧
  • 8. Arrays y An array in PHP is actually an ordered map. A map is a type that maps values to keys. array() = creates arrays <?php $arr = array("foo" => "bar", 12 => true); key = either an integer or a string. echo $arr["foo"]; // bar echo $arr[12]; // 1 value = any PHP type. ?> if no key given (as in example), the PHP <?php array(5 => 43, 32, 56, "b" => 12); interpreter uses (maximum of the integer indices + array(5 => 43, 6 => 32, 7 => 56, "b" => 12); y( ) 1). ?> if an existing key, its value will be overwritten. <?php p p $arr = array(5 => 1, 12 => 2); can set values in an array foreach ($arr as $key => $value) { echo $key, ‘=>’, $value); } $arr[] = 56; // the same as $arr[13] = 56; unset() removes a key/value pair $arr[ x ] $arr["x"] = 42; // adds a new element unset($arr[5]); // removes the element unset($arr); // deletes the whole array $a = array(1 => 'one', 2 => 'two', 3 => 'three'); array_values() makes reindexing effect unset($a[2]); (indexing numerically) $b = array_values($a); l ($ ) ?> ٨ *Find more on arrays
  • 9. Constants A constant is an identifier (name) for a simple value. A constant is case‐sensitive by A constant is an identifier (name) for a simple value A constant is case sensitive by default. By convention, constant identifiers are always uppercase. <?php // Valid constant names define("FOO", "something"); define("FOO2", "something else"); define("FOO_BAR", "something more"); // Invalid constant names (they shouldn’t start shouldn t You can access constants // with a number!) anywhere in your script define("2FOO", "something"); without regard to scope. // This is valid, b t should b avoided: Thi i lid but h ld be id d // PHP may one day provide a “magical” constant // that will break your script define("__FOO__", "something"); ?> ٩
  • 10. Operators Example Is the same as • Arithmetic Operators: +, ‐, *,/ , %, ++, ‐‐ x+=y x=x+y x‐=y x=x‐y • Assignment Operators: =, +=, = =, /=, Assignment Operators: = += ‐=, *= /= %= x*=y * x=x*y * x/=y x=x/y x%=y x=x%y • Comparison Operators: ==, !=, >, <, >=, <= • Logical Operators: &&, ||, ! • String Operators: . and .= (for string concatenation) $a = "Hello "; $b = $a . "World!"; // now $b contains "Hello World!" $a = "Hello "; $a .= "World!"; ١٠
  • 11. Conditionals: if else Can execute a set of code depending on a condition <html><head></head> if (condition) ( ) <!‐‐ if‐cond.php COMP519 ‐‐> <body> code to be executed if condition is true; <?php $d=date("D"); $d d (" ") else echo $d, “<br/>”; code to be executed if condition if ($d=="Fri") echo "Have a nice weekend! <br/>"; is false; else l echo "Have a nice day! <br/>"; $x=10; date() is a built-in PHP function if ($x==10) ($ 10) that can be called with many { different parameters to return the echo "Hello<br />"; echo "Good morning<br />"; date (and/or local time) in } various f i formats t ?> In this case we get a three letter </body> /b d </html> string for the day of the week. ١١
  • 12. Conditionals: switch Can select one of many sets of lines to execute <html><head></head> <body> <!–‐ switch‐cond.php COMP519 ‐‐> switch (expression) <?php $x = rand(1,5); // random integer { echo “x = $ <br/><br/>”; $x / / case label1: switch ($x) code to be executed if expression = { case 1: label1; echo "Number 1"; ; break; break; case label2: case 2: echo "Number 2"; code to be executed if expression = break; label2; case 3: break; echo "Number 3"; break; default: default: code to be executed echo "No number between 1 and 3"; if expression is different break; b k } from both label1 and label2; ?> break; } </body> </html> ١٢
  • 13. Looping: while and do‐while Can loop depending on a condition Can loop depending on a condition <html><head></head> <html><head></head> <body> y <body> y <?php <?php $i=1; $i=0; while($i <= 5) do { { echo "The number is $i <br />"; $i++; $i++; echo "The number is $i <br />"; } } ?> while($i <= 10); ?> </body> </html> </body> </html> loops through a block of code if and as long as, a specified if, as condition is true loops through a block of code once, and then repeats the loop as long as a special condition is true (so will always execute at least once) ١٣
  • 14. Looping: for and foreach p g Can loop depending on a "counter" <?php <?php for ($i=1; $i<=5; $i++) $a_array = array(1, 2, 3, 4); { foreach ($a_array as $value) echo "Hello World!<br />"; { } $value = $value * 2; ?> echo “$value <br/> n”; } ?> loops through a block of code a specified number of times <?php $a_array=array( a b c ); $a array=array("a","b","c"); foreach ($a_array as $key => $value) { echo $key." = ".$value."n"; } ?> loops through a block of code for each element in an p g array ١۴
  • 15. User Defined Functions Can define a function using syntax such as the following: <?php function foo($arg 1, $arg 2, /* ..., */ $arg n) ($ g_ , $ g_ , / , / $ g_ ) Can also define conditional functions, functions functions { echo "Example function.n"; within functions, and recursive functions. return $retval; } ?> Can return a value of any type <?php <?php function square($num) function small_numbers() { { return $num * $num; return array (0, 1, 2); } } echo square(4); list ($zero, $one, $two) = small_numbers(); ?> echo $zero, $one, $two; ?> <?php function takes_array($input) { echo "$input[0] + $input[1] = ", $input[0]+$input[1]; $input[0] } takes_array(array(1,2)); ?> ١۵
  • 16. Variable Scope The scope of a variable is the context within which it is defined. <?php ? h $a = 1; /* limited variable scope */ function Test() { The scope is local within functions, echo $ h $a; and hence the value of $a is /* reference to local scope variable */ undefined in the “echo” statement. } Test(); ?> ? <?php <?php p p function Test() $a = 1; { $b = 2; global static $a = 0; static function Sum() echo $a; { refers to its global $a++; does not lose its value. global $a $b; $a, version. version } $b = $a + $b; Test1(); } Test1(); Sum(); Test1(); echo $b; ?> ?> ١۶
  • 17. Including Files The include() statement includes and evaluates the specified file. <?php vars.php function foo() <?php { global $color; $color = 'green'; $fruit = 'apple'; include ('vars.php‘); ?> echo "A $color $fruit"; } test.php <?php / /* vars.php is in the scope of foo() so * p p p () * $fruit is NOT available outside of this * echo "A $color $fruit"; // A * scope. $color is because we declared it * * as global. */ include 'vars.php'; foo(); // A green apple echo "A $color $fruit"; // A green apple echo "A $color $fruit"; // A green ?> ?> *The scope of variables in “included” files depends on where the “include” file is added! ١٧ You can use the include_once, require, and require_once statements in similar ways.
  • 18. PHP Information The phpinfo() function is used to output PHP information about the version installed on the  server, parameters selected when installed, etc. , parameters selected when installed, etc. <html><head></head> INFO_GENERAL The configuration line, <!– info.php COMP519 php.ini location, <body> build date, <?php Web Server, // Show all PHP information System and more phpinfo(); ?> INFO_CREDITS PHP 4 credits <?php INFO_CONFIGURATION Local and master values // Show only the general information for php directives phpinfo(INFO_GENERAL); phpinfo(INFO GENERAL); ?> INFO_MODULES Loaded modules </body> </html> INFO_ENVIRONMENT Environment variable information INFO_VARIABLES All predefined variables from EGPCS INFO_LICENSEPHP license information INFO_ALL INFO ALL Shows all of the above (default) ١٨
  • 19. Server Variables The $_SERVER array variable is a reserved variable that contains all server information.  <html><head></head> h l h d /h d <body> <?php echo "Referer: " . $_SERVER["HTTP_REFERER"] . "<br />"; _ [ _ ] echo "Browser: " . $_SERVER["HTTP_USER_AGENT"] . "<br />"; echo "User's IP address: " . $_SERVER["REMOTE_ADDR"]; ?> </body> </html> The $_SERVER is a super global variable, i.e. it's available in all scopes of a PHP script. ١٩
  • 20. File Open The fopen("file_name","mode") function is used to open files in PHP. r Read only. r+ Read/Write. w Write only. w+ Read/Write. a Append. Append a+ Read/Append. Read/Append x Create and open for write only. x+ Create and open for read/write. <?php For w, and a, if no file exists, it tries to create it (use with caution, i.e. $fh=fopen("welcome.txt","r"); check that this is the case, otherwise you’ll overwrite an existing file). ?> For x if a file exists, it returns an error. <?php if If th f the fopen() f ti iis unable to open the specified file, it () function bl t th ifi d fil ( !($fh=fopen("welcome.txt","r")) ) returns 0 (false). exit("Unable to open file!"); ?> ٢٠
  • 21. File Workings fclose() closes a file. feof() determines if the end is true true. fgetc() reads a single character fgets() reads a line of data fwrite(), fputs () writes a string with and without n (), p g file() reads entire f into an array file <?php <?php $myFile = "welcome.txt"; welcome.txt ; $myFile = "welcome.txt"; welcome.txt ; if (!($fh=fopen($myFile,'r'))) $fh = fopen($myFile, 'r'); exit("Unable to open file."); $theData = fgets($fh); while (!feof($fh)) fclose($fh); { echo $theData; $x=fgetc($fh); ?> echo $x; } fclose($fh); ?> <?php p p $myFile = "testFile.txt"; $fh = fopen($myFile, 'a') or die("can't open file"); $stringData = "New Stuff 1n"; <?php fwrite($fh, $stringData); $lines = fil (' l $li file('welcome.txt'); ') $stringData = "New Stuff 2n"; New 2n ; foreach ($lines as $l_num => $line) fwrite($fh, $stringData); { fclose($fh); echo "Line #{$l_num}:“ .$line.”<br/>”; ?> } ?> ٢١
  • 22. Form Handling Any form element is automatically available via one of the built‐in PHP variables (provided the element has a “name” defined with  y o e e e t s auto at ca y a a ab e a o e o t e bu t a ab es (p o ded t e e e e t as a a e de ed t it). <html> <‐‐ form.html COMP519 ‐‐> <body> <form action="welcome.php" method="POST"> Enter your name: <input type="text" name="name" /> <br/> Enter your age: <input type="text" name="age" / <br/> " " " " /> b / <input type="submit" /> <input type="reset" /> </form> </body> </html> <html> $_POST _ <!–‐ welcome.php COMP 519 ‐‐> ! l h contains all POST data. <body> $_GET Welcome <?php echo $_POST["name"].”.”; ?><br /> contains all GET data. You are <?php echo $_POST["age"]; ?> years old! </body> </html> ٢٢
  • 23. Cookie Workings setcookie(name,value,expire,path,domain) creates cookies. ki ( l i h d i ) ki <?php setcookie("uname", $_POST["name"], time()+36000); ?> <html> <body> NOTE: <p> setcookie() must appear Dear <?php echo $_POST["name"] ?>, a cookie was set on this BEFORE <html> (or any output) page! The cookie will be active when the client has sent the cookie back to the server. as it’s part of the header </p> information sent with the page. </body> </html> <html> <body> $_COOKIE <?php contains all COOKIE data. if ( isset($_COOKIE["uname"]) ) echo "Welcome " . $_COOKIE["uname"] . "!<br />"; else isset() echo "You are not logged in!<br />"; finds out if a cookie is set ?> </body> </html> / use the cookie name as a variable ٢٣
  • 24. Getting Time and Date date() and time () formats a time or a date formats a time or a date. <?php //Prints something like Monday like: echo date("l"); date() returns a string formatted according to //Like: Monday 15th of January 2003 05:51:38 AM the specified format. echo date("l jS of F Y h:i:s A"); //Like: Monday the 15th echo date("l the jS"); ?> <?php p p $nextWeek = time() + (7 * 24 * 60 * 60); // 7 days; 24 hours; 60 mins; 60secs time() returns current Unix echo 'Now: '. date('Y‐m‐d') ."n"; timestamp echo 'Next Week: '. date('Y‐m‐d', $nextWeek) ."n"; ?> *Here is more on date/time formats: http://uk.php.net/manual/en/function.date.php ٢۴
  • 25. Required Fields in User‐Entered Data A multipurpose script which asks users for some basic contact information and then checks to  l h h k f b f d h h k see that the required fields have been entered. <html> <!‐‐ form_checker.php COMP519 ‐‐> <head> <title>PHP Form example</title> </head> <body> <?php /*declare some functions*/ Print Function P i t F ti function print_form($f_name, $l_name, $email, $os) { ?> <form action="form_checker.php" method=“POST"> First Name: <input type="text" name="f_name" value="<?php echo $f_name?>“ /> <br/> Last Name <b>*</b>:<input t L tN <b>*</b> <i t type="text" name="l_name" value="<?php echo $l "t t" "l " l "<? h h $l_name?>“ /> <b /> ?>“ <br/> Email Address <b>*</b>:<input type="text" name="email" value="<?php echo $email?>“ /> <br/> Operating System: <input type="text" name="os" value="<?php echo $os?>“ /> <br/><br/> <input type="submit" name="submit" value="Submit“ /> <input type=“reset“ /> </form> <?php } //** end of “print_from” function ٢۵
  • 26. Check and Confirm Functions function check_form($f_name, $l_name, $email, $os) { if (!$l_name||!$email){ echo "<h3>You are missing some required fields!</h3>"; print_form($f_name, $l_name, $email, $os); } else{ confirm_form($f_name, $l_name, $email, confirm form($f name $l name $email $os); } } //** end of “check_form” function function confirm_form($f_name, $l_name, $email, $os) { ?> <h2>Thanks! Below is the information you have sent to us.</h2> <h3>Contact Info</h3> <?php echo "N h "Name: $f$f_name $l $l_name <br/>"; b/ " echo "Email: $email <br/>"; echo "OS: $os"; } //** end of “confirm_form” function ٢۶
  • 27. Main Program /*Main Program*/ if (!$_POST["submit"]) { ?> <h3>Please enter your information</h3> <p>Fields with a "<b>*</b>" are required.</p> <?php print_form("","","",""); } else{ check_form($_POST["f_name"],$_POST["l_name"],$_POST["email"],$_POST["os"]); } ?> </body> </html> ٢٧
  • 28. Introduction to SQL SQL is an ANSI (American National Standards Institute) standard computer language  for accessing and manipulating databases. • SQL stands for Structured Query Language • using SQL can you can – access a database – execute queries, and retrieve data – insert, delete and update records • SQL works with database programs like MS Access, DB2, Informix, MS SQL Server, Oracle, Sybase, mySQL, etc. Unfortunately, there are many different versions. But, they must support the same major keywords in a similar manner such as SELECT, UPDATE, DELETE, INSERT, WHERE, etc. Most of the SQL database programs also have their own proprietary extensions! ٢٨
  • 29. SQL Database Tables A database most often contains one or more tables. Each table is identified by a name (e.g. "Customers" or "Orders"). Tables contain records (rows) with data. For example, a table called "Persons": LastName L tN FirstName Fi tN Address Add City Cit Hansen Ola Timoteivn 10 Sandnes Svendson Tove Borgvn 23 Sandnes Pettersen Kari Storgt 20 Stavanger The table above contains three records (one for each person) and four columns (LastName, FirstName, Address, and City).
  • 30. SQL Queries With SQL, you can query a database and have a result set returned. A query like thi lik this: SELECT LastName FROM Persons; gives a result set like this: LastName Hansen a se Svendson Pettersen The mySQL database system requires a semicolon at the end of the SQL statement!
  • 31. SQL Data Languages The query and update commands together form the Data Manipulation Language (DML) part of SQL: • SELECT - extracts data from a database table • UPDATE - updates data in a database table • DELETE - deletes data from a database table • INSERT INTO - inserts new data into a database table The Data Definition Language (DDL) part of SQL permits database tables to be created or deleted: • CREATE TABLE - creates a new database table • ALTER TABLE - alters (changes) a database table • DROP TABLE - deletes a database table • CREATE INDEX - creates an index (search key) • DROP INDEX - deletes an index *Here we will use some of them in mySQL ٣١
  • 32. Logging into mySQL Server You Y can l i log into our mySQL server f SQL from Li Linux b typing i the prompt by i in h bash‐2.05b$ mysql ‐h mysql martin –u martin Welcome to the MySQL monitor. Commands end with ; or g. Your MySQL connection id is 209201 to server version: 5.0.22 Type 'help;' or 'h' for help. Type 'c' to clear the buffer. mysql> From here you can create modify and drop tables, and modify the data in your tables create, modify, tables tables. But first, you must specify which database on the server you want to use (you have only one, however). mysql> use martin; Database changed ٣٢
  • 33. Technical note • Y probably d ’t need t worry about thi b t th You b bl don’t d to b t this, but thought I would ht ld mention it here… Most books and on‐line tutorials assume the database server is running on the same machine as everything else, and that the user is "root". root Neither of these are true here. Wherever you see "localhost", replace it by "mysql" Wherever you see "root", replace it with your username. (Ignore this if you don’t understand it for now, or are not consulting other references.) ٣٣
  • 34. Creating a Table You Y can create a table you might use f the upcoming project. For example, bl i h for h i j l mysql> CREATE TABLE students( Hit Enter after each line (if you ‐> num INT NOT NULL AUTO_INCREMENT, want). MySQL doesn’t try to ‐> f_name VARCHAR(48), interpret the command itself until ‐> l_name VARCHAR(48), it sees a semicolon (;) ‐> student_id INT, (The “->” characters you see are ‐> email VARCHAR(48), not typed by you.) ‐> PRIMARY KEY(num)); Query OK, 0 rows affected (0.02 sec) *If the server gives you a big ERROR, just try again from the top! ٣۴
  • 35. Viewing The Table Structure Use DESCRIBE to see the structure of a table mysql> DESCRIBE students; +‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐+‐‐‐‐‐+‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐+ | Field | Type | Null | Key | Default | Extra | +‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐+‐‐‐‐‐+‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐+ | num | int(11) | NO | PRI | NULL | auto_increment | | f_name | varchar(48) | YES | | NULL | | | l_name | varchar(48) | YES | | NULL | | | student_id | int(11) | YES | | NULL | | | email | varchar(48) | YES | | NULL | | +‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐+‐‐‐‐‐+‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐+ ٣۵
  • 36. Inserting Data Using INSERT INTO you can insert a new row into your table. For example, table example mysql> INSERT INTO students ‐> VALUES(NULL,’Russell’,’Martin’,396640,‘martin@csc.liv.ac.uk'); Query OK, 1 row affected (0.00 sec) Using SELECT FROM you select some data from a table. g y mysql> SELECT * FROM students; +‐‐‐‐‐+‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐+ | num | f_name | l name | student id | email f name l_name student_id | +‐‐‐‐‐+‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐+ | 1 | Russell | Martin | 396640 | martin@csc.liv.ac.uk | +‐‐‐‐‐+‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐+ 1 row in set (0.00 sec) ٣۶
  • 37. Inserting Some More Data You Y can repeat i t inserting until all d t i entered i t th t bl ti til ll data is t d into the table. mysql> INSERT INTO students ‐> VALUES(NULL,‘James',‘Bond',007,'bond@csc.liv.ac.uk'); Query OK, 1 row affected (0.01 sec) mysql> SELECT * FROM students; +‐‐‐‐‐+‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐+ | num | f_name | l_name | student_id | email | +‐‐‐‐‐+‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐+ | 1 | Russell | Martin | 396640 | martin@csc.liv.ac.uk | | 2 | James | Bond | 7 | bond@csc liv ac uk | bond@csc.liv.ac.uk +‐‐‐‐‐+‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐+ 2 rows in set (0.00 sec) Note: The value “NULL” in the “num” field is automatically replaced by the SQL interpreter as the “auto increment” option was selected when the table was defined auto_increment defined. ٣٧
  • 38. Getting Data Out of the Table • The SELECT command is the main way of getting data out of a table or set of table, tables. SELECT * FROM students; Here the asterisk means to select (i.e. return the information in) all columns. You can specify one or more columns of data that you want, such as SELECT f name,l name FROM students; f_name,l_name +---------+--------+ | f_name | l_name | +---------+--------+ | Russell | Martin | | James | Bond | +---------+--------+ 2 rows in set (0.00 sec) ٣٨
  • 39. Getting Data Out of the Table (cont.) • You can specify other information that you want in the query using the WHERE clause WHERE clause. SELECT * FROM students WHERE l_name=‘Bond’; +-----+---------+--------+------------+----------------------+ | num | f_name | l_name | student_id | email | +-----+---------+--------+------------+----------------------+ | 2 | James | Bond | 7 | bond@csc.liv.ac.uk | +-----+---------+--------+------------+----------------------+ 1 row in set (0.00 sec) SELECT student_id, email FROM students WHERE l_name Bond ; l name=‘Bond’; +------------+----------------------+ | student_id | email | +------------+----------------------+ | 7 | bond@csc.liv.ac.uk @ | +------------+----------------------+ 1 row in set (0.00 sec) ٣٩
  • 40. Altering the Table The Th ALTER TABLE statement i used to add or d is d dd drop columns i an existing table. l in i i bl mysql> ALTER TABLE students ADD date DATE; Query OK, 2 rows affected (0.00 sec) OK (0 00 Records: 2 Duplicates: 0 Warnings: 0 mysql> SELECT * FROM students; +‐‐‐‐‐+‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐+ | num | f name | l name | student id | email f_name l_name student_id | date | +‐‐‐‐‐+‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐+ | 1 | Russell | Martin | 396640 | martin@csc.liv.ac.uk | NULL | | 2 | James | Bond | 7 | bond@csc liv ac uk | NULL | bond@csc.liv.ac.uk +‐‐‐‐‐+‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐+ 2 rows in set (0.00 sec) ۴٠
  • 41. Updating the Table The UPDATE statement is used to modify data in a table table. mysql> UPDATE students SET date='2007‐11‐15' WHERE num=1; Query OK, 1 row affected (0.01 sec) OK (0 01 Rows matched: 1 Changed: 1 Warnings: 0 mysql> SELECT * FROM students; +‐‐‐‐‐+‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐+ | num | f name | l name | student id | email f_name l_name student_id | date | +‐‐‐‐‐+‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐+ | 1 | Russell | Martin | 396310 | martin@csc.liv.ac.uk | 2007‐11‐15 | | 2 | James | Bond | 7 | bond@csc.liv.ac.uk | NULL | +‐‐‐‐‐+‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐+ 2 rows in set (0.00 sec) Note that the default date format is “YYYY‐MM‐DD” and I don’t believe this ۴١ default setting can be changed.
  • 42. Deleting Some Data The DELETE statement is used to delete rows in a table. mysql> DELETE FROM students WHERE l_name='Bond'; Query OK, 1 row affected (0.00 sec) mysql> SELECT * FROM students; +‐‐‐‐‐+‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐+ | num | f_name | l_name | student_id | email | date | +‐‐‐‐‐+‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐+ | 1 | Russell | Martin | 396310 | martin@csc.liv.ac.uk | 2006‐11‐15 | +‐‐‐‐‐+‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐+ 1 row in set (0.00 sec) ۴٢
  • 43. The Final Table We’ll first add another column, update the (only) record, then insert more , p ( y) , data. mysql> ALTER TABLE students ADD gr INT; yq g ; Query OK, 1 row affected (0.01 sec) Records: 1 Duplicates: 0 Warnings: 0 mysql> SELECT * FROM students; +‐‐‐‐‐+‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐+ | num | f_name | l_name | student_id | email | date | gr | +‐‐‐‐‐+‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐+ | 1 | Russell | Martin | 396310 | martin@csc.liv.ac.uk | 2007‐11‐15 | NULL | + +‐‐‐‐‐+‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐+ + + + + + + + 1 row in set (0.00 sec) mysql> UPDATE students SET gr=3 WHERE num=1; Query OK, 1 row affected (0.00 sec) Rows matched: 1 Changed: 1 Warnings: 0 mysql> SELECT * FROM students; +‐‐‐‐‐+‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐+ | num | f_name | l_name | student_id | email | date | gr | +‐‐‐‐‐+‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐+ | 1 | Russell | Martin | 396310 | martin@csc.liv.ac.uk | 2007‐11‐15 | 3 | +‐‐‐‐‐+‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐‐‐‐‐‐‐+‐‐‐‐‐‐+ 1 row in set (0.00 sec) mysql> INSERT INTO students VALUES(NULL,‘James',‘Bond',007,'bond@csc.liv.ac.uk‘,‘2007‐11‐15’, 1); . . ۴٣ .
  • 44. The Final Table (cont.) . . . . . . mysql> INSERT INTO students VALUES(NULL,‘Hugh,‘Milner',75849789,‘hugh@poughkeepsie.ny‘, CURRENT_DATE, 2); Note: CURRENT_DATE is a built-in SQL command which (as expected) gives the current (local) date. mysql> SELECT * FROM students; +-----+---------+----------+------------+----------------------------+------------+------+ | num | f_name | l_name | student_id | email | date | gr g | +-----+---------+----------+------------+----------------------------+------------+------+ | 1 | Russell | Martin | 396310 | martin@csc.liv.ac.uk | 2007-11-15 | 3 | | 5 | Kate | Ash | 124309 | kate@ozymandius.co.uk | 2007-11-16 | 3 | | 3 | James | Bond | 7 | bond@csc.liv.ac.uk | 2007-11-15 | 1| | 4 | Bob | Jones | 12190 | bob@nowhere.com | 2007-11-16 | 3 | | 6 | Pete | Lofton | 76 | lofton@iwannabesedated.com | 2007-11-17 | 2 | | 7 | Polly | Crackers | 1717 | crackers@polly.org | 2007-11-17 | 1| | 8 | Hugh | Milner | 75849789 | hugh@poughkeepsie.ny | 2007-11-17 | 2 | +-----+---------+----------+------------+----------------------------+------------+------+ 7 rows in set (0.00 sec) mysql> exit ۴۴ Bye
  • 45. Other SQL Commands • SHOW tables; gives a list of tables that have been defined in the database • ALTER TABLE students DROP email; would drop the “email” column from all records • DROP TABLE students; deletes the entire “students” table, and its definition (use students (use  the DROP command with extreme care!!) • DELETE FROM students; removes all rows from the “students” table (so once  again, use the DELETE command with great caution), the table definition remains to be used again • A more useful command is something like DELETE FROM students WHERE (num > 5) AND (num <= 10); which selectively deletes students based on their “num” values (for example) num example). • HELP; gives the SQL help • HELP DROP; gives help on the DROP command, etc. ۴۵
  • 46. Backing up/restoring a mySQL database • You can back up an entire database with a command such as mysqldump –h mysql –u martin martin > backup.sql (Run from the Unix command line )line.) • This gives a script containing SQL commands to reconstruct the table structure (of all tables) and all of the data in the table(s). ( ) () • To restore the database (from scratch) you can use this type of Unix command: mysql –h mysql –u martin martin < backup sql h u backup.sql (Use with caution, as this can overwrite your database.) • Other commands are possible to backup/restore only certain tables or items in tables etc if that is what you desire For tables, etc. desire. example mysqldump –h mysql –u martin martin books clients> backup.sql stores information about the “books” and “clients” tables in the books clients “martin” database. ۴۶
  • 47. Putting Content into Your Database with PHP We can simply use PHP functions and mySQL queries together: • Connect to the database server and login (this is the PHP command to do so) mysql_connect("host","username","password"); Host: mysql • Choose the database Database: martin mysql_select_db("database"); Username: martin Password: <blank> • Send SQL queries to the server to add, delete, and modify data mysql_query("query"); (use the exact same query string as you would normally use in SQL, without the trailing semi‐colon) • Close the connection to the database server (to ensure the information is stored properly) mysql_close(); • Note: For this to work properly on the UoL server, you must access the PHP script through the cgi server (http://cgi.csc.liv.ac.uk/~martin/getstuff.php for example). ۴٧
  • 48. Student Database: data_in.php <html> <head> <title>Putting Data in the DB</title> </head> <body> <?php /*insert students into DB*/ if(isset($_POST["submit"])) { $db = mysql_connect("mysql”, ”martin"); mysql_select_db("martin"); $date=date("Y-m-d"); $d t d t ("Y d") /* G t th current date in the right SQL f Get the t d t i th i ht format t */ $sql="INSERT INTO students VALUES(NULL,'“ . $_POST[“f_name"] . "','“ . $_POST["l_name"] . "',“ . $_POST["student_id"] . ",'“ . $_POST["email"] . "','“ . $date . "',“ . $_POST["gr"] . ")"; /* construct the query */ mysql_query($sql); /* execute the query */ mysql_close(); echo"<h3>Thank you. The data has been entered.</h3> n"; echo'<p><a href="data_in.php">Back to registration</a></p>‘ . “n”; echo'<p><a href "data out php">View the student lists</a></p>‘ .”n”; href="data_out.php">View ”n”; } ۴٨
  • 49. Student Database: data_in.php _ p p else { ?> <h3>Enter your items into the database</h3> <form action="data_in.php" method="POST"> First Name: <input type="text" name=“f_name“ /> <br/> Last Name: <input type="text" name=“l_name“ /> <br/> p yp ID: <input type="text" name=“student_id“ /> <br/> email: <input type="text" name=“email“ /> <br/> Group: <select name="gr"> <option value ="1">1</option> p p <option value ="2">2</option> <option value ="3">3</option> </select><br/><br/> <input type="submit" name="submit“ /> <input type="reset“ /> p yp p yp </form> <?php } ?> </body> </html> ۴٩
  • 50. Getting Content out of Your Database with PHP ith Similarly, Similarly we can get some information from a database: • Connect to the server and login, choose a database mysql_connect("host","username","password"); l t("h t" " "" d") mysql_select_db("database"); • S d an SQL query t th server t select d t from th d t b Send to the to l t data f the database into an array i t $result=mysql_query("query"); • Either, look into a row and a fieldname , $num=mysql_numrows($result); $variable=mysql_result($result,$i,"fieldname"); • Or, fetch rows one by one $row=mysql_fetch_array($result); • Close the connection to the database server mysql_close(); ۵٠
  • 51. Student Database: data_out.php <html> <head> <title>Getting Data out of the DB</title> </head> <body> <h1> Student Database </h1> <p> Order the full list of students by <a href="data_out.php?order=date">date</a>, <href="data_out.php?order=student_id">id</a>, or by <a href="data_out.php?order=l_name">surname</a>. </p> <p> <form action="data_out.php" method="POST"> Or only see the list of students in group <select name="gr"> <option value ="1">1</option> <option value ="2">2</option> <option value ="3">3</option> </select> <br/> <input type="submit" name="submit“ /> </form> </p> ۵١
  • 52. Student Database: data_out.php <?php p p /*get students from the DB */ $db = mysql_connect("mysql",“martin"); mysql_select_db(“martin", $db); switch($_GET["order"]){ case 'date': $sql = "SELECT * FROM students ORDER BY date"; break; case ‘student_id': $sql = "SELECT * FROM students ORDER BY student_id"; break; case ‘l_name': $sql = "SELECT * FROM students ORDER BY l_name"; break; default: $sql = “SELECT * FROM students”; break; } if(isset($_POST["submit"])){ $sql = “SELECT * FROM students WHERE gr=“ . $_POST["gr"]; } $result=mysql_query($sql); /* execute the query */ while($row=mysql_fetch_array($result)){ echo "<h4> Name: “ . $row["l_name"] . ', ‘ . $row["f_name"] . "</h4> n"; echo "<h5> ID: “ . $row[“student_id"] . "<br/> Email: “ . $row["email"] . "<br/> Group: “ . $row["gr"] . "<br/> Posted: “ . $row["date"] . "</h5> n"; } mysql_close(); ?> </body> </html> ۵٢
  • 53. Can Do Even More with PHP • Can create tables in PHP • Can delete C d l t rows and columns d l • Can make updates • Can make queries to several tables • Can get connected to several databases * Find more iinformation on PHP/ SQL Fi d f ti PHP/mySQL ۵٣
  • 54. Learning Outcomes In these last lectures you have learned What is SQL How to access mySQL database How to create a basic mySQL database How to use some basic queries How t H to use PHP and mySQL d SQL ۵۴
  • 55. Using several tables • mySQL (like any other database system that uses SQL) is a relational database, meaning that it’s designed to work with multiple tables, and it allows you to make queries that involve several tables tables. • Using multiple tables allows us to store lots of information without much duplication. duplication • Allows for easier updating (both insertion and deletion). • We can also perform different types of queries, combining the queries information in different ways depending upon our needs. ۵۵
  • 56. Advanced queries • Suppose that we have defined several tables as follows: pp mysql> describe clients; +-----------+-------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-----------+-------------+------+-----+---------+----------------+ | client_id | int(11) | NO | PRI | NULL | auto_increment | | f_name | varchar(20) | YES | | NULL | | | l_name | varchar(30) | NO | | | | | address dd | varchar(40) | YES | h (40) | NULL | | | city | varchar(30) | YES | | NULL | | | postcode | varchar(12) | YES | | NULL | | +-----------+-------------+------+-----+---------+----------------+ 6 rows i set (0 01 sec) in t (0.01 ) mysql> describe purchases; +-------------+---------+------+-----+---------+----------------+ | Fi ld Field | T Type | N ll | K Null Key | D f lt | Extra Default E t | +-------------+---------+------+-----+---------+----------------+ | purchase_id | int(11) | NO | PRI | NULL | auto_increment | | client_id | int(11) | NO | | | | | d t date | d t date | NO | | | | +-------------+---------+------+-----+---------+----------------+ ۵۶ 3 rows in set (0.00 sec)
  • 57. mysql> describe itemlist; +-------------+---------+------+-----+---------+----------------+ | Field | T pe Type | N ll | Ke | Defa lt | E t a Null Key Default Extra | +-------------+---------+------+-----+---------+----------------+ | item_id | int(11) | NO | PRI | NULL | auto_increment | | purchase_id | int(11) | NO | | | | | book id book_id | int(11) | NO | | | | +-------------+---------+------+-----+---------+----------------+ 3 rows in set (0.00 sec) mysql> describe books; +---------+-------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +---------+-------------+------+-----+---------+----------------+ | book id | int(11) book_id | NO | PRI | NULL | auto_increment | auto increment | title | varchar(50) | NO | | | | | pages | int(11) | YES | | NULL | | +---------+-------------+------+-----+---------+----------------+ 3 rows in set (0.00 sec) (0 00 mysql> ۵٧
  • 58. The idea here is that clients can make multiple purchases. Each purchase will be assigned a unique id, but can consist of multiple items. Each item is a book, which can be purchased by many different people people. Defining the tables in this fashion allows us to avoid ( g (excessive)) repetition of information, and lets us query the data in different fashions. The “id” fields are the keys that we use to tie the various tables together, namely a customer (or client) with “client id” will make several client_id purchases. We can identify their purchases by searching for matches of the client_id in the purchases table. Similarly, we can find the actual items that comprise a particular purchase by searching for the purchase id key in the itemlist table purchase_id table. ۵٨
  • 59. Populate the tables • Suppose that we have this data in the tables: mysql> select * from clients; +-----------+---------+--------+--------------------------+----------------+----------+ | client_id | f_name | l_name | address | city | postcode | +-----------+---------+--------+--------------------------+----------------+----------+ | 1 | Russell | Martin | Dept of Computer Science | Liverpool p p p | L69 3BX | | 2 | Bob | Milnor | 12 Peachtree Ln | Liverpool | L12 3DX | | 3 | Sarah | Ford | 542b Jersey Rd | West Kirby | L43 8JK | | 4 | Larry | Vance | 76 Jarhead Ln | Liverpool | L12 4RT | | 5 | Paul | Abbott | 90 Crabtree Pl | Leamingotn Spa | CV32 7YP | +-----------+---------+--------+--------------------------+----------------+----------+ 5 rows in set (0.01 sec) mysql> select * from books; +---------+---------------------+-------+ | book_id | title | pages | +---------+---------------------+-------+ | 1 | Linux in a Nutshell | 120 | | 2 | Learning SQL | 289 | | g 3 | Abstract Algebra | 320 | | 4 | Rising Sun | 830 | | 5 | Round the Moon | 136 | | 6 | Blackbeard | 292 | +---------+---------------------+-------+ 6 rows in set (0.00 sec) (0 00 mysql> ۵٩
  • 60. mysql> SELECT * FROM purchases; +-------------+-----------+------------+ | purchase_id | client_id | date | +-------------+-----------+------------+ | 1 | 1 | 2007-11-09 | | 2 | 1 | 2007-11-10 | | 4 | 2 | 2007-11-20 | | 5 | 4 | 2007-11-20 | | 6 | 3 | 2007 11 21 | 2007-11-21 | 7 | 5 | 2007-11-25 | | 8 | 3 | 2007-11-25 | +-------------+-----------+------------+ 7 rows in set (0.00 sec) mysql> SELECT * FROM itemlist; +---------+-------------+---------+ | item_id | purchase_id | book_id | +---------+-------------+---------+ | 1 | 1 | 2 | | 2 | 1 | 6 | | 3 | 1 | 3 | | 4 | 2 | 4 | | 5 | 2 | 5 | | 6 | 4 | 5 | | 7 | 4 | 6 | | 8 | 5 | 1 | | 9 | 5 | 3 | | 10 | 6 | 5 | | 11 | 7 | 2 | | 12 | 8 | 3 | +---------+-------------+---------+ 12 rows in set (0.00 sec) mysql> ۶٠
  • 61. Advanced Queries • We can link these tables together by queries of this type: myql> SELECT * from clients, purchases WHERE clients.client_id=purchases.client_id ORDER BY purchase_id; +----------+---------+--------+--------------------------+----------------+----------+-------------+-----------+------------+ |client_id | f_name | l_name | address | city | postcode | purchase_id | client_id | date | -----------+---------+--------+--------------------------+----------------+----------+-------------+-----------+------------+ | 1 | Russell | Martin | Dept of Computer Science | Liverpool | L69 3BX | 1| 1 | 2007-11-09 | | 1 | Russell | Martin | Dept of Computer Science | Liverpool | L69 3BX | 2| 1 | 2007 11 10 | 2007-11-10 | 2 | Bob | Milnor | 12 Peachtree Ln | Liverpool | L12 3DX | 4| 2 | 2007-11-20 | | 4 | Larry | Vance | 76 Jarhead Ln | Liverpool | L12 4RT | 5| 4 | 2007-11-20 | | 3 | Sarah | Ford | 542b Jersey Rd | West Kirby | L43 8JK | 6| 3 | 2007-11-21 | | 5 | Paul | Abbott | 90 Crabtree Pl | Leamingotn Spa | CV32 7YP | 7| 5 | 2007-11-25 | | 3 | Sarah | Ford | 542b Jersey Rd | West Kirby | L43 8JK | 8| 3 | 2007-11-25 | +-----------+---------+--------+--------------------------+----------------+----------+-------------+-----------+------------+ 7 rows in set (0 01 sec) (0.01 mysql> So you can see that this query gives us all of the purchase orders that have been placed by the clients (but not the number of items, or the items ۶١ themselves).
  • 62. You can see that the “client_id” field is repeated. This is because we selected all columns ( (using the * option) in both tables, and it appears in each table. g p ) pp • To avoid this repeated information, we can make a query like: mysql> SELECT clients.client_id, f_name, l_name, address, city, postcode, purchases.purchase_id,date from clients, purchases WHERE clients.client_id=purchases.client_id ORDER BY purchase_id; +-----------+---------+--------+--------------------------+----------------+----------+-------------+------------+ | client_id | f_name | l_name | address ce d a e a e add ess | city c y | postcode | purchase id | date pos code pu c ase_ d da e | +-----------+---------+--------+--------------------------+----------------+----------+-------------+------------+ | 1 | Russell | Martin | Dept of Computer Science | Liverpool | L69 3BX | 1 | 2007-11-09 | | 1 | Russell | Martin | Dept of Computer Science | Liverpool | L69 3BX | 2 | 2007-11-10 | | 2 | B b | Milnor | 12 P ht Ln Bob Mil Peachtree L | Liverpooll | L12 3DX Li | 4 | 2007 11 20 | 2007-11-20 | 4 | Larry | Vance | 76 Jarhead Ln | Liverpool | L12 4RT | 5 | 2007-11-20 | | 3 | Sarah | Ford | 542b Jersey Rd | West Kirby | L43 8JK | 6 | 2007-11-21 | | 5 | Paul | Abbott | 90 Crabtree Pl | Leamingotn Spa | CV32 7YP | g p 7 | 2007-11-25 | | 3 | Sarah | Ford | 542b Jersey Rd | West Kirby | L43 8JK | 8 | 2007-11-25 | +-----------+---------+--------+--------------------------+----------------+----------+-------------+------------+ 7 rows in set (0.00 sec) mysql> The “NATURAL JOIN” option can obtain the same result as above, as they share a single key. NATURAL JOIN mysql> SELECT * FROM clients NATURAL JOIN purchases; ۶٢
  • 63. • We need not select all columns: mysql> SELECT f_name,l_name, purchases.purchase_id FROM clients NATURAL JOIN purchases ORDER BY purchase_id; +---------+---------+-------------+ | f_name | l_name | purchase_id | +---------+---------+-------------+ | Russell | Martin | 1 | | Russell | Martin | 2 | | Bob | Milnor | 4 | | Larry | Vance | 5 | | Sarah | Ford | 6 | | Paul | Abbott | 7 | | Sarah | Ford | 8 | +---------+----------+-------------+ 7 rows i set (0 00 sec) in t (0.00 ) mysql> ۶٣
  • 64. More Complex Queries • We can create most any type of query that you might think of with a (more complicated) “WHERE” clause: mysql> SELECT purchases.purchase_id, f_name, l_name, date FROM purchases, clients WHERE purchases.client_id=clients.client_id; +-------------+---------+--------+------------+ + + + + + | purchase_id | f_name | l_name | date | +-------------+---------+--------+------------+ | 1 | Russell | Martin | 2007 11 09 | 2007-11-09 | 2 | Russell | Martin | 2007-11-10 | | 4 | Bob | Milnor | 2007-11-20 | | 5 | Larry | Vance | 2007-11-20 | 2007 11 20 | 6 | Sarah | Ford | 2007-11-21 | | 7 | Paul | Abbott | 2007-11-25 | | 8 | Sarah | Ford | 2007-11-25 | 2007 11 25 +-------------+---------+--------+------------+ 7 rows in set (0.00 sec) mysql> ۶۴
  • 65. More Complex Queries (cont ) (cont.) • Find the purchases by the person named “Ford” “Ford”. mysql> SELECT purchases.purchase_id, f_name, l_name, date FROM purchases, clients WHERE (purchases.client_id=clients.client_id) AND (l_name='Ford'); +-------------+--------+--------+------------+ + + + + + | purchase_id | f_name | l_name | date | +-------------+--------+--------+------------+ | 6 | Sarah | Ford | 2007-11-21 | 2007 11 21 | 8 | Sarah | Ford | 2007-11-25 | +-------------+--------+--------+------------+ 2 rows in set (0.01 sec) mysql> ۶۵
  • 66. Querying multiple tables • In addition, we can query many tables (i.e. more than two) at once: • First we’ll find all the purchases by a person with ll_name= Martin . we ll name=‘Martin’ mysql> select p y q purchases.purchase_id, f_name, l_name, date FROM p , , , purchases, clients WHERE (purchases.client_id=clients.client_id) AND (l_name='Martin') ORDER BY purchases.purchase_id; +-------------+---------+--------+------------+ | purchase_id | f_name | l_name | date | +-------------+---------+--------+------------+ | 1 | Russell | Martin | 2007-11-09 | | 2 | Russell | Martin | 2007-11-10 | +-------------+---------+--------+------------+ 2 rows in set (0.00 sec) mysql> ۶۶
  • 67. Querying multiple tables (cont.) • Now let’s find out the items (the “book_id”) in each purchase: mysql> SELECT purchases.purchase_id, f l> h h id f_name, ll_name, d t date, itemlist.book_id FROM purchases, clients, itemlist WHERE (purchases.client_id=clients.client_id) AND (l_name='Martin') AND (purchases.purchase_id=itemlist.purchase_id) (purchases purchase id=itemlist purchase id) ORDER BY purchases.purchase_id; +-------------+---------+--------+------------+---------+ | purchase_id | f_name | l_name | date | book_id | +-------------+---------+--------+------------+---------+ | 1 | Russell | Martin | 2007-11-09 | 2 | | 1 | Russell | Martin | 2007-11-09 | 6 | | 1 | Russell | Martin | 2007-11-09 | 3 | | 2 | Russell | Martin | 2007-11-10 | 5 | | 2 | Russell | Martin | 2007-11-10 | 4 | +-------------+---------+--------+------------+---------+ 5 rows in set (0.00 sec) mysql> ۶٧
  • 68. Querying multiple tables (cont.) • Finally we can find the actual book titles by querying all four tables at once: mysql> SELECT purchases.purchase_id, f_name, l_name, date, itemlist.book_id, title FROM purchases clients itemlist, books purchases, clients, itemlist WHERE (purchases.client_id=clients.client_id) AND (l_name='Martin') AND (purchases.purchase_id=itemlist.purchase_id) AND (itemlist.book_id books.book_id) (itemlist book id=books book id) ORDER BY purchases.purchase_id; +-------------+---------+--------+------------+---------+------------------+ | purchase_id | f_name | l_name | date | book_id | title | +-------------+---------+--------+------------+---------+------------------+ | 1 | Russell | Martin | 2007-11-09 | 6 | Blackbeard | | 1 | Russell | Martin | 2007-11-09 | 2 | Learning SQL | | 1 | Russell | Martin | 2007-11-09 | 3 | Abstract Algebra | | 2 | Russell | Martin | 2007-11-10 | 4 | Rising Sun | | 2 | Russell | Martin | 2007-11-10 | 2007 11 10 5 | Round the Moon | +-------------+---------+--------+------------+---------+------------------+ 5 rows in set (0.00 sec) mysql> ۶٨
  • 69. Querying multiple tables (cont.) • As before, we need not select all of the columns: mysql> SELECT purchases.purchase_id, title FROM purchases, clients, itemlist, books WHERE (purchases client id=clients client id) AND (purchases.client_id=clients.client_id) (l_name='Martin') AND (purchases.purchase_id=itemlist.purchase_id) AND (itemlist.book_id=books.book_id) ORDER BY purchases.purchase id; purchases.purchase_id; +-------------+------------------+ | purchase_id | title | +-------------+------------------+ | 1 | Blackbeard | | 1 | Learning SQL | | 1 | Abstract Algebra | | 2 | Rising Sun | | 2 | Round the Moon | +-------------+------------------+ 5 rows in set (0.00 sec) mysql> ۶٩
  • 70. Using aliases in queries • Especially long queries might benefit from the SQL capability for using aliases. mysql> select p.purchase_id, title FROM purchases AS p, clients AS c, itemlist AS i, books WHERE (p.client_id=c.client_id) AND (l_name='Martin') AND (p.purchase_id=i.purchase_id) AND (i.book_id books.book_id) (i.book id=books.book id) ORDER BY p.purchase id; p.purchase_id; +-------------+------------------+ | purchase_id | title | +-------------+------------------+ | 1 | Blackbeard | | 1 | Learning SQL | | 1 | Abstract Algebra | | 2 | Rising Sun | | 2 | Round the Moon | +-------------+------------------+ 5 rows in set (0.00 sec) An alias uses the SQL keyword ‘AS’ to associate a new identifier with a table. It should appear after the table name and before the alias. Once a table is aliased you must use that alias everywhere iin th O t bl i li d t th t li h the ٧٠ SQL query.
  • 71. Searching tables The SQL “wildcard” character is the % symbol That is it can literally represent wildcard symbol. is, anything. Using it we can build searches like the following: mysql> SELECT * FROM clients WHERE l_name LIKE '%a%'; +-----------+---------+--------+--------------------------+----------------+----------+ + + + + + + + | client_id | f_name | l_name | address | city | postcode | +-----------+---------+--------+--------------------------+----------------+----------+ | 1 | Russell | Martin | Dept of Computer Science | Liverpool | L69 3BX | | 4 | Larry | Vance | 76 Jarhead Ln | Liverpool | L12 4RT | | 5 | Paul | Abbott | 90 Crabtree Pl | Leamingotn Spa | CV32 7YP | +-----------+---------+--------+--------------------------+----------------+----------+ 3 rows in set (0.00 sec) This above search finds all data that has a letter “a” in the user_id column. mysql> SELECT * FROM clients where l_name LIKE '%an%'; +-----------+--------+--------+---------------+-----------+----------+ | client_id | f_name | l_name | address | city | postcode | +-----------+--------+--------+---------------+-----------+----------+ | 4 | Larry | Vance | 76 Jarhead Ln | Liverpool | L12 4RT | +-----------+--------+--------+---------------+-----------+----------+ 1 row in set (0.00 sec) ٧١
  • 72. Searching tables (cont.) mysql> SELECT clients.client_id, f_name, l_name FROM clients NATURAL JOIN purchases where l_name LIKE '%a%'; +-----------+---------+--------+ | client_id | f_name | l_name | +-----------+---------+--------+ | 1 | Russell | Martin | | 1 | Russell | Martin | | 4 | Larry | Vance | | 5 | Paul | Abbott | +-----------+---------+--------+ 4 rows in set (0.00 sec) mysql> SELECT clients client id f name l name FROM clients purchases WHERE clients.client_id, f_name, l_name clients, (l_name LIKE '%a%') AND (clients.client_id=purchases.client_id) AND (clients.client_id > 1); +-----------+--------+--------+ | client_id | f_name | l_name | +-----------+--------+--------+ | 4 | Larry | Vance | | 5 | Paul | Abbott | +-----------+--------+--------+ 2 ٧٢ rows in set (0.00 sec)
  • 73. More on PHP and SQL To increase security of your PHP/SQL setup (and to make it easier to change the database you use), it’s recommended that you build an “include” file that will have use) it s include the information you use to connect to the database. <?php /* Save this as db_login.php (or whatever you like) and include it in your php script. */ // Here’s the information to connect to the database. $db_host = ‘mysql’; $db_database=‘martin’; $db_username= martin ; $db username=‘martin’; $db_password=‘’; ?> If someone tries to view this file through their browser, the PHP interpreter will process it and return a blank page to the user (there’s no HTML in the file). ٧٣
  • 74. Connecting to the database g Now you can build your PHP script as follows (using the commands that we discussed previously): <?php require_once (‘db_login.php’); $connection = mysql_connect($db_host, $db_username, $db_password); if (!$connection) /* check if the connection was actually successful */ { exit(“Could not connect to the database: <br/>” . htmlspecialchars(mysql_error()) ); } else { // more statements here. . . } ?> Note: The function ‘htmlspecialchars()’ converts special characters in a string into their HTML escape sequences (like ‘&’ into ‘&amp;’ and so forth). This can also be used to increase the security of your code by and help thwart attacks on your database by passing it information that your client has submitted before trying ٧۴ to insert it in your database.
  • 75. MySQL queries inside of PHP Your mySQL queries from a PHP script are the same as they are as when you’re using the mySQL program from the command line with one difference… the queries do not have a semi-colon at the end. Aside f A id from this difference, all of the regular SQL commands and k thi diff ll f th l d d keywords are available d il bl when you perform your queries. You Y can create new t bl alter, and d l t th from inside of a PHP script, and you can t tables, lt d delete them f i id f i t d also insert and delete rows of tables as normal too. For any such operation, you’ll likely want to check to see if it’s successful (especially if you’re trying to insert into or extract data from the database). <?php // Assuming a valid database connection has been established. // Build the query string by assigning variables... $query = $select . $column . $from . $tables . $where; $result = mysql_query($query); if(!$result) { exit(“Could not query the database: <br/>” . / htmlspecialchars(mysql_error()) ); } else { // process the data } ?> ٧۵
  • 76. Processing the results of a query • There Th are two main PHP methods to f h the results of an SQL query, these b i i h d fetch h l f h being ‘mysql_fetch_row()’ and ‘mysql_fetch_array()’. <?php // Assuming a database connection, and a valid query string. $result = mysql_query( $query ); while ($result_row = mysql_fetch_row($result)) { echo $result_row[2] . ‘<br/>’; } ?> The ‘mysql fetch row()’ command fetches the query results as an enumerated array mysql_fetch_row() (an array that uses numerical indices), one row at a time, returning FALSE when there are no more rows (ending the ‘while’ loop in this case). ٧۶
  • 77. Processing the results of a query (cont.) • mysql_fetch_array can get a row of results as an associative array (using strings as the array indices) It takes a result as its first parameter and an optional indices). parameter, second parameter as a way to bind the results in the array. • If MYSQL_ASSOC is specified, the results are indexed using the column names in the query. If MYSQL_NUM is specified, then the numerical array indices (starting query MYSQL NUM specified at zero) access the results. The default value MYSQL_BOTH returns an array with both types. while ( $row = mysql_fetch_array($result, MYSQL_ASSOC) ) { echo $row[“title”] . ‘<br/>’; } • Using a statement like ‘mysql_fetch_array($result, MYSQL_NUM)’ is essentially equivalent to the statement ‘mysql_fetch_row($result)’ as they both return arrays stored with numerical indices indices. • The ‘mysql_fetch_array()’ command can be used to save memory by specifying, say, MYSQL_ASSOC, instead of the default value. ٧٧
  • 78. Other useful PHP/SQL related functions • The f Th function ‘mysql_data_seek($result, $ l )’ can b used to move the iinternall i ‘ l d k($ l $value)’ be d h result pointer (which is advanced automatically when commands like ‘mysql_fetch_array()’ is called). This allows you, for example, to reprocess the results of a query (without having to access the database again). ‘mysql_data_seek($result, 0);’ will reset the pointer to the initial row in the query result (but is an error if the query result was empty). ( q y p y) • ‘mysql_num_rows ($result);’ returns the number of rows in the query result. • ‘mysql_affected_rows();’ gives the number of affected rows by the last INSERT, DELETE, UPDATE DELETE UPDATE, or REPLACE query. query • ‘mysql_insert_id();’ returns the ID generated by the AUTO_INCREMENT of the most recent query if there was one, or ‘0’ if there was no AUTO_INCREMENT ٧٨ value.