SlideShare a Scribd company logo
1 of 119
Download to read offline
PHP (and a little MySQL) for
 the Default Library Techie

                                                Lisa Bartle, Reference Librarian
                                                Cal. State University, San Bernardino
                                                LBartle@csusb.edu
                                                909-537-7552
                                                An Infopeople Workshop



 PHP (and a Little MySQL) for the Default Library Techie Summer 2006 - This material has been created by Lisa Bartle for the Infopeople Project
 [infopeople.org], supported by the U.S. Institute of Museum and Library Services under the provisions of the Library Services and Technology Act,
 administered in California by the State Librarian. Any use of this material should credit the author and funding source.
Introductions

  •Lab assistant
  •Participants
     –Name
     –Position
     –What you hope to do with PHP
PHP (and a Little MySQL) for the Default Library Techie




          Assumptions for This Class


      1. You know html code (e.g., tables, forms).
      2. You understand the basics of databases (e.g., fields,
         records, truncation).
      3. A little programming experience in any language is
         useful for this class but not essential (for example, you
         know what a variable is).
PHP (and a Little MySQL) for the Default Library Techie




                         Goals for This Class


              1. Not to teach everything about PHP, but provide
                 the basic knowledge for an online database.
              2. Explain just the code, not setting up a server.
              3. Provide a solid grounding so the books are not
                 as formidable.
PHP (and a Little MySQL) for the Default Library Techie




        Diagram of Web Applications




    Borrowed from MySQL/PHP Database Applications, 2nd ed. by Brad Bulger, Jay Greenspan, and
    David Wall.
PHP (and a Little MySQL) for the Default Library Techie




                                      What is PHP?



                A scripting language most suitable for
                   online database management.
PHP (and a Little MySQL) for the Default Library Techie




                                      PHP Benefits

    • Open source, so it’s free
    • Hosting is inexpensive
    • PHP can be embedded in html files using .php
      file extension
    • Easy to learn
    • Works powerfully and intimately with MySQL
      and the web
PHP (and a Little MySQL) for the Default Library Techie




                           PHP More Benefits
    •Works well with Apache – also open source
    •Parse complex strings
    •Communicate with many credit card processing systems
    •Communicate with many protocols, including IMAP &
    POP3 (email), NNTP (usenet), and DNS (hostnames &
    addresses)
    •Native database support for over 25 db products including
    dBase, FilePro, FrontBase, IBM DB2, Hyperwave, mSQL,
    MySQL, Sybase, Unix dbm, Access, and many others
       oAccess may be more difficult to connect
PHP (and a Little MySQL) for the Default Library Techie




                            Who’s Using PHP?




                        Go to http://www.php.net/usage.php to
                        find current usage statistics.
                        http://www.abc-lit.com
PHP (and a Little MySQL) for the Default Library Techie




                            Recommendations
                             for Text Editors

          • EditPlus2 from ES-Computing (free)
          • NoteTab Light from Fookes Software (free)
          • PHP Designer from MP Software (free)
          • Crimson Editor from Ingyu Kang (free)
PHP (and a Little MySQL) for the Default Library Techie




        It All Starts with the Database

                   The MySQL Connection
PHP (and a Little MySQL) for the Default Library Techie




                                What is MySQL?


        • A database system often used for web-
          accessible databases
        • A relational database management system
          (RDMS), like Microsoft’s Access, using SQL
PHP (and a Little MySQL) for the Default Library Techie




                         MySQL Introduction
         • Pronounced “My Ess Que Ell,” according to
           the MySQL reference manual.
         • Can handle small databases or very large ones
            (ex. 50 million records, 60,000 tables and
           about 5,000,000,000 rows; maximum table
           size is 65536 terabytes, but operating systems
           have limitations).

         Look at the MySQL reference manual (downloads.mysql.com/docs/refman-5.0-en.pdf).
PHP (and a Little MySQL) for the Default Library Techie




                                MySQL Benefits
     • Open source, so it’s free
     • Designed to work intimately with PHP and the web
     • Dependable code back to 1980s and fully backward
       compatible
     • Can operate with a variety of operating systems:
            o     Unix; FreeBSD; Mac OS X; Solaris; Windows 9x,
                  Me, NT, 2000, XP, and Server 2003
                  (Microsoft products are not the best with MySQL)
PHP (and a Little MySQL) for the Default Library Techie




              How Is Your Data Stored?


                           • Access
                           • Excel
                           • Something else
PHP (and a Little MySQL) for the Default Library Techie




                          If You Have Data …



          • Using Access or Excel you may want to
            convert to MySQL using an online converter
          • Intelligent Converters has several for-fee
            programs at http://www.convert-in.com
PHP (and a Little MySQL) for the Default Library Techie




               If You Don’t Have Data …
       • Create a database using MySQL client
PHP (and a Little MySQL) for the Default Library Techie




                           More If You Don’t
                            Have Data …

       • Create a database using Access or Excel
       • Create a database using phpMyAdmin
              o     a tool written in PHP for the administration of a
                    MySQL server over the Web
              o     often included with the operating system
PHP (and a Little MySQL) for the Default Library Techie




         phpMyAdmin Table Creation
PHP (and a Little MySQL) for the Default Library Techie




                    To Maintain Your Data
      • Use Access or Excel to update, then convert
        to MySQL using a converter
PHP (and a Little MySQL) for the Default Library Techie




                                        MySQL data
     INSERT INTO 'people' VALUES('Joann', 'M',
     'Aardappel', "", 'Pine Bluff', 'AR', 'Fontana',
     'CA', 'San Bernardino County Sun', '2000-10-09');
     INSERT INTO 'people' VALUES('Louie', 'R',
     'Aboytes', "", 'Mesa', 'AZ', 'Loma Linda', 'CA',
     'San Bernardino County Sun', '2001-01-05');
     INSERT INTO 'people' VALUES('Edith', "",
     'Abramson', 'Gimble', 'St. Paul', 'MN', 'Redlands',
     'CA', 'San Bernardino County Sun', '2000-11-18');
     INSERT INTO 'people' VALUES('Antonia', "",
     'Acevedo', 'Bermudez', "", 'Mexico', 'Fontana',
     'CA', 'San Bernardino County Sun', '2000-11-14');
PHP (and a Little MySQL) for the Default Library Techie




                    To Maintain Your Data



       • Use Access or Excel to update, then convert
         to MySQL using a converter
       • Use phpMyAdmin to update
PHP (and a Little MySQL) for the Default Library Techie




                  phpMyAdmin Data Input
PHP (and a Little MySQL) for the Default Library Techie




                                    Housekeeping


    1. Open Internet Explorer
    2. Go to Tools > Internet Options > Advanced
    3. Put an X next to: Enable folder view for FTP
       sites
PHP (and a Little MySQL) for the Default Library Techie




                                         Our Project
         Go to http://phpclass.infopeople.org/search.html
PHP (and a Little MySQL) for the Default Library Techie




                        The PHP Connection
PHP (and a Little MySQL) for the Default Library Techie




                          PHP Start and Stop



                         •PHP code starts                 <?php


                         •PPH code ends                   ?>



   example1.php
PHP (and a Little MySQL) for the Default Library Techie




                                           Comments

                • Explain the purpose of the coding
                • Help you and others read the code
                • Help you when you’ve forgotten what it
                  all means
PHP (and a Little MySQL) for the Default Library Techie




                          Comment Structure


  // begin each line inside the PHP code

  # begin each line inside the PHP code

  /* begin and */ end several lines inside
  the PHP code
PHP (and a Little MySQL) for the Default Library Techie




                              Comment Examples
    <?php
    //Purpose: to create a form for patrons’ questions
    ?>
    ----------------------------
    <?php
    ###### Show Results to User ######
    ?>
    ----------------------------
    <?php
    /*
    Purpose: to create a form for patrons’ questions
    Author: Lisa Bartle
    Date: Nov. 6, 2006
    */
    ?>
PHP (and a Little MySQL) for the Default Library Techie




                                           Exercise 1

     Open up Notepad and get to coding!
PHP (and a Little MySQL) for the Default Library Techie




                           “Hello_Librarians”:
                           First PHP Example
                                 <h2>Infopeople PHP class</h2>
       Code                      <?php
                                 print "<p>Hello librarians!";
                                 ?>




          User Sees



   example1.php
PHP (and a Little MySQL) for the Default Library Techie




                                   PHP and HTML

                  •HTML can be outside of PHP coding
                  •HTML can be inside of the code, but must
                  be inside quotation marks with a print
                  statement
                  •PHP statements end in a semi-colon



   example1.php
PHP (and a Little MySQL) for the Default Library Techie




                               Outputting Data


    •Echo -- a language construct or structure for a
    single argument.
    •Print -- a language construct, which can have
    multiple arguments and more complex
    expressions.



                      We will use PRINT in this class.
PHP (and a Little MySQL) for the Default Library Techie




                    Echo & Print Example

                   <?php
Code               Echo "Infopeople PHP Presentation";
                   Print "<P>Hello librarians.";
                   ?>




User Sees



   example2.php
PHP (and a Little MySQL) for the Default Library Techie




                      What is a Variable?
      • A variable is a place to store information.
      • Information stored in a variable can be defined
        by the programmer.
      • Information stored in a
      variable can come from a
      user using a form.
PHP (and a Little MySQL) for the Default Library Techie




                                             Variables
      • A variable always begins with a $ then the
        variable name.
      • Variables are case sensitive and alpha-numeric.
      • Do not start a variable with a number.
      • All the variables below are different.
            $book
            $amount
            $Amount
            $AmoUnT
            $AMOUNT
PHP (and a Little MySQL) for the Default Library Techie




                             Variable Example
          <?php
          Print "<h2>Infopeople PHP Presentation
          </h2><br>";
          print "<p>Hello librarians! <br>";
          $date="Nov. 6, 2006";
          print "Today’s date is $date";
          ?>




   example3.php
PHP (and a Little MySQL) for the Default Library Techie




                             Printing Variables


          <?php
          $date="Nov. 6, 2006";
          print "Today’s date is $date";
          Print "Today’s date is "; print $date;

          ?>




   example3.php
PHP (and a Little MySQL) for the Default Library Techie




                                    Date Function

                  • Use date() to display the date and time
                  • Can display in multiple ways
                              Jul. 12, 2006
                              July 12, 2006
                              7/12/2006
                              2006/07/12

   example7.php
PHP (and a Little MySQL) for the Default Library Techie




                                       Date Display
                                    $datedisplay=date("Y/m/d");
                                    print $datedisplay;
                                    # If the date is November 6, 2005
                                    # It would display as 2005/11/06



                                   $showdate=date("l, F j, Y");
                                   print $showdate;
                                   # If the date is November 6, 2005
                                   # It would display as
                                   # Sunday, November 6, 2005

            See handout “Displaying the Date Using
   example7.php
                           Date()”
PHP (and a Little MySQL) for the Default Library Techie




                                           Exercise 2

     Open up Notepad and get to coding!
PHP (and a Little MySQL) for the Default Library Techie




                         Profession Example




   profession.php
PHP (and a Little MySQL) for the Default Library Techie




                     The HTML Connection
PHP (and a Little MySQL) for the Default Library Techie




                                                 Forms


                     Forms provide an interface for users to
                             query your database.
PHP (and a Little MySQL) for the Default Library Techie




                                   Forms HTML
 <-- form tag goes before the form objects -->
 <form>

 [form objects go here]
 [radio buttons, pull-down menus, text boxes]

 [submit button, cancel button]

 </form>
PHP (and a Little MySQL) for the Default Library Techie




                                   Radio Buttons

<INPUT type="radio" name="sex" value="M"> Male<BR>
<INPUT type="radio" name="sex" value="F">
Female<BR>




                   Name becomes the variable name.
                   Value is what the variable is holding.
   example9.html
PHP (and a Little MySQL) for the Default Library Techie




                          Pull-Down Menus
  <p>City of death: <select name="deathcity"
  size="1">
  <option selected value="">Search all cities in
  database</option>
  <option value="Fontana">Fontana</option>
  <option value="Loma Linda">Loma Linda</option>
  <option value="Redlands">Redlands</option>
  <option value="San Bernardino">San
  Bernardino</option>
  <option value="Victorville">Victorville</option>
  </select>

   Name =variable name.
   Value =what variable is holding.
   example10.html
PHP (and a Little MySQL) for the Default Library Techie




                                         Text Boxes

  <input TYPE= "text" NAME="anyname" SIZE="20"
  MAXLENGTH="40">




                               Name =variable name.

   example11.html
PHP (and a Little MySQL) for the Default Library Techie




                                      Check Boxes

       Libraries should get more<p>
       <input TYPE="checkbox" NAME="money"
       VALUE="Yes" checked> Money <br>
       <input TYPE="checkbox" NAME="respect"
       VALUE="Yes"> Respect


    Name=variable name
    Value=what variable is holding.

   example13.html
PHP (and a Little MySQL) for the Default Library Techie




                      Submit/Reset Buttons

    <input TYPE="submit" NAME="Search"
    VALUE="Search it!">
    <input TYPE="reset" NAME="Cancel"
    VALUE="Clear Form">




   example14.html
PHP (and a Little MySQL) for the Default Library Techie




                                    Form Action

 <-- not just form tag, but form action -->

 <form action="file,URL,or path" method="post">

 [form objects here]

 </form>
PHP (and a Little MySQL) for the Default Library Techie




                        The PHP Connection
PHP (and a Little MySQL) for the Default Library Techie




                                           Operators


                                 • Arithmetic operators
                                 • Assignment operators
                                 • Comparison operators



                            See handout “Operators.”
PHP (and a Little MySQL) for the Default Library Techie




                      Arithmetic Operators


                         $a + $b                          //addition
                         $a - $b                          //subtraction
                         $a * $b                          //multiplication
                         $a / $b                          //division




   example6.php
PHP (and a Little MySQL) for the Default Library Techie




                  Assignment & Arithmetic
                        Operators

       <?php
       $a=15;
       $b=30;
       $total=$a+$b;
       Print $total;
       Print "<p><h1> $total </h1>";
       //total is 45
       ?>




   example6.php
PHP (and a Little MySQL) for the Default Library Techie




                   Comparison Operators
                         Equal                                  $a == $b

                         Not Equal                              $a != $b
                                                                $a <> $b

                         Less Than                              $a < $b
                         Less Than or Equal to                  $a <= $b
                         Greater Than                     $a > $b
                         Greater Than or Equal to               $a >= $b

                              See handout “Operators”
PHP (and a Little MySQL) for the Default Library Techie




       Difference Between = and ==

                           = Assigns a value to a variable

                           == Checks the value of a variable




                            See handout “Operators.”
PHP (and a Little MySQL) for the Default Library Techie




                                              If … Else
      If (condition)
      {                                                   If ($user=="Lisa")
            Statement;                                     {
                                                           Print "Hello Lisa.";
      }                                                    }
      Else                                                Else {
                                                          Print "You aren't Lisa.";
      {                                                   }
            Statement;
      }

                                    No THEN in PHP
PHP (and a Little MySQL) for the Default Library Techie




       If (condition)                               ElseIf
       {
             Statement;                                   If ($user=="Lisa")
                                                           {
       }                                                  Print "Hello Lisa.";
       Elseif (condition)                                  }
                                                          Elseif ($user=="Mo")
       {
                                                           {
             Statement;                                   Print "Hello Mo.";
       }                                                   }
                                                          Else
       Else                                                {
       {                                                  Print "Who are you?";
             Statement;                                    }

       }
PHP (and a Little MySQL) for the Default Library Techie




           While Loops                                    <?php
                                                          $count=0;
                                                          While ($count<5)
         While (condition)                                {
         {                                                Print "Hello Lisa.";
                                                          $count=$count + 1;
           Statement;                                     }
         }                                                #Another way to say
                                                          #to say that is
                                                          #$count++;
                                                          ?>




   example8.php
PHP (and a Little MySQL) for the Default Library Techie




                         Profession Example
    1. Go to                 http://phpclass.infopeople.org/lisa/profession.php




   profession.php
PHP (and a Little MySQL) for the Default Library Techie




                   Questions to Think About


                   1. What is the first step for this code?


                   2. What kind of php structures will be necessary?




   example15.php
PHP (and a Little MySQL) for the Default Library Techie




                                           Exercise 3
PHP (and a Little MySQL) for the Default Library Techie




                   Top Errors & Messages

              1. Missing semi-colon.
              2. Misspelled variables and missing $.
              3. Incomplete pairs for quotation marks, parentheses, curly
              brackets, etc.



                                              See handout
                  “Common PHP Mistakes and Error
                            Messages”
PHP (and a Little MySQL) for the Default Library Techie




                      Our Sample Database
            • This class’s prepared database is called obituaries.
            • The file is obituaries.sql.
            • It is an index of people’s names who have had
              obits listed in the newspaper. It is for patron’s
              genealogical research.
            • The table called people has our data.
              Records: 100
              Fields:      11
                        See handout “Organize Your
                     Database and Server Information”
PHP (and a Little MySQL) for the Default Library Techie




               Download Search.html to
                   Your Directory
     Go to http://phpclass.infopeople.org/search.html

    1. Click View > Source
    2. Save the file as search.html
       to your desktop.
    3. Copy the file from your
       desktop into your directory.


        You will not need to create the search form
                        from scratch.
PHP (and a Little MySQL) for the Default Library Techie




                                          search.php


              >>Creates connection to server & database
              •Alters input for safety
              •Creates SQL query
              •Displays the results
              >>Close the connection to database
PHP (and a Little MySQL) for the Default Library Techie




                Connect to the Server

   Mysql_connect() is the function used to
   connect to the server.

   mysql_connect("hostaddress", "myusername",
   "mypassword") or die ("message");


         Die() is a function for an output message and to
         terminate the current script.
PHP (and a Little MySQL) for the Default Library Techie




       Mysql_connect() Structure



    $connection=mysql_connect("hostaddress",
    "myusername", "mypassword") or die
    ("message");
PHP (and a Little MySQL) for the Default Library Techie




        Mysql_connect() Example
# Create connection to database
# Define variables
$hostaddress="phpclass.phpclass.
infopeople.org";
$myusername="phpclass";
$mypassword="infopeople";
$connection=mysql_connect($hostaddress
, $myusername, $mypassword) or die
("Can’t connect to server.");
PHP (and a Little MySQL) for the Default Library Techie




                             Close Connection


               Mysql_close() is the function to close the
               connection to the server.


                            mysql_close($connection);
PHP (and a Little MySQL) for the Default Library Techie




             Connect to the Database

  Mysql_select_db() is the function to select your
  MySQL database.


mysql_select_db("database") or die ("Message");
PHP (and a Little MySQL) for the Default Library Techie




                          Mysql_select_db()

     #$database="obituaries";
     #$tablename="people";
     $result=mysql_select_db($database)
     or die("Database could not be
     selected");
PHP (and a Little MySQL) for the Default Library Techie




                       Alter Input for Safety


             • Creates connection to database
             >>Alters input for safety
             • Creates SQL query
             • Displays the results
             • Close the connection to database
PHP (and a Little MySQL) for the Default Library Techie




                       Trim(), Strip_tags(),
                           Strtolower()
 • Trim removes whitespace at the beginning and end of a string.
 • Strip_tags tries to remove PHP & HTML tags from a string.
 • Strtolower converts alpha characters to lowercase.

                 $anyname=trim($anyname);
                 $anyname=strip_tags($anyname);
                 $anyname=strtolower($anyname);

   search.php
PHP (and a Little MySQL) for the Default Library Techie




                                           Exercise 4


     Open up Notepad and get to coding!
PHP (and a Little MySQL) for the Default Library Techie




                             Create SQL Query


             • Creates connection to database
             • Alters input for safety
             >>Creates SQL query
             • Displays the results
             • Close the connection to database
PHP (and a Little MySQL) for the Default Library Techie




                                   Concatenation
        “A union by chaining or linking together.” Use a
        period to link together strings.
  <?php
  $string1="Hello";
  $string2="Librarians";
  $string3=$string1." ".$string2;
  Print $string3;
  print "<p>";
  Print $string1." ".$string2;
  ?>

 example5.php
PHP (and a Little MySQL) for the Default Library Techie




                   Escaping the Character

         If the string has a set
         of double quotation
         marks that must
         remain visible, use
         the  [backslash]                                <?php
         before the quotation                             $heading=""Lisa's
                                                          Books"";
         marks so PHP does
                                                          Print $heading;
         not act on them and                              ?>
         only displays them.
   example16.php
PHP (and a Little MySQL) for the Default Library Techie




                        The SQL Connection
PHP (and a Little MySQL) for the Default Library Techie




        Diagram of Web Applications




    Borrowed from MySQL/PHP Database Applications, 2nd ed. by Brad Bulger, Jay Greenspan, and
    David Wall.
PHP (and a Little MySQL) for the Default Library Techie




                                  What is SQL?


        • Structured Query Language
        • A database access language standard
        • All SQL-capable databases support a
          common subset of SQL
               o   Access, MySQL, some Oracle databases, etc.
PHP (and a Little MySQL) for the Default Library Techie




         SQL Select Query Template


        SELECT [field],[field] from [table] WHERE
        [field] [operator] [parameter or input]
        ORDER BY [field] [ASC or DESC];
PHP (and a Little MySQL) for the Default Library Techie




                       SQL Query Examples
            Database: obituaries
            Table: people
            Fields: lastname, firstname, middlename,
            maidenname, newsdate, newsyear


      •SELECT lastname, firstname from people where newsyear
      > 2000;
      •SELECT lastname, firstname from people where newsyear
      > 2000 and newsyear < 2003;
      •SELECT lastname, firstname from people where newsyear
      BETWEEN 2000 and 2003;

                Numbers do not need quotation marks in
PHP (and a Little MySQL) for the Default Library Techie




                       SQL Query Examples
            Database: obituaries
            Table: people
            Fields: lastname, firstname, middlename,
            maidenname, newsdate, newsyear

      •SELECT * from people where lastname = "Jones";
      •SELECT * from people where lastname LIKE "Jones%";
      •SELECT * from people where lastname LIKE "%Jones";
      •SELECT * from people where lastname LIKE "%Jones%"
      ORDER BY lastname ASC, firstname ASC;



                        Text needs quotation marks in
                        SQL.
PHP (and a Little MySQL) for the Default Library Techie




                  PHP & SQL in the Query

       SELECT * from people where
       lastname LIKE "%Jones%" ORDER BY
       lastname ASC;

       $query="SELECT * from people
       where lastname LIKE "%Jones%"
       ORDER BY lastname ASC";
PHP (and a Little MySQL) for the Default Library Techie




             Variables in the PHP/SQL
                      Query
       $query="SELECT * from people
       where lastname LIKE "%Jones%"
       ORDER BY lastname ASC";

       $query="SELECT * from "
       .$tablename. " where lastname
       LIKE "%" .$anyname. "%" ORDER
       BY lastname ASC";
PHP (and a Little MySQL) for the Default Library Techie




   Match Against In Boolean Mode
        $query="SELECT * from " .$tablename. "
        WHERE MATCH(firstname, middlename,
        lastname, maidenname) AGAINST
        ('$anyname' IN BOOLEAN MODE) AND
        newsyear>= " .$newsyear1. " AND
        newsyear<=" .$newsyear2. " ORDER BY
        lastname ASC";
                                                          Red=PHP
                                                          Purple=SQL
PHP (and a Little MySQL) for the Default Library Techie




              SQL Troubleshooting Tips
  Build the SQL statement slowly, piece by piece.

  # Keep what is working and comment it out so
  # that you can start from success when you
  # need to start over.
  # $query="SELECT * from ".$tablename;
  # This works
  $query="SELECT * from ".$tablename;
  Print the query so you can tell where it is breaking down.
  Print $query;
PHP (and a Little MySQL) for the Default Library Techie




                                           SQL Query


    If ($deathcity=="") {$deathcityquery=" ";}
    else {$deathcityquery=" and
      deathcity="".$deathcity.""";}
PHP (and a Little MySQL) for the Default Library Techie




                                More SQL Query
 If ($anyname=="")
 {
 $query="SELECT * from " . $tablename. " WHERE
   newsyear >=".$newsyear1." AND
   newsyear<=".$newsyear2.$deathcityquery."
   ORDER BY lastname ASC";
 }
 else
 {
 $query="SELECT * from " . $tablename. " WHERE
   match(firstname, middlename, lastname,
   maidenname) against ('$anyname' in boolean
   mode) and newsyear >=".$newsyear1." AND
   newsyear<=".$newsyear2.$deathcityquery."
   ORDER BY lastname ASC";
 • }
PHP (and a Little MySQL) for the Default Library Techie




                  Download sql_query.php

     Sql_query.php is available in the main directory
     of the ftp server.

            • Copy the file to your desktop.
            • Open it.
            • Copy the query and place it under the header
            Create SQL Query.
PHP (and a Little MySQL) for the Default Library Techie




                       True Boolean Queries

     We have a textbox, $anyname, in our obituary
     search form. We want it to be Boolean searchable.
     Such as:

                         (peek or byrd) and (mary or ellen)



                                      How do we do
                                      it?
PHP (and a Little MySQL) for the Default Library Techie




                     Alter the Input for SQL

          Think of our old AltaVista searches:

               +alice –wonderland +columbia


          We need to use PHP to substitute the AND, OR,
          NOT that the users input so that SQL can
          understand it.
PHP (and a Little MySQL) for the Default Library Techie




                      Create Boolean String


       # Insert an initial plus-sign so
       # the first term or phrase is
       # included as a mandatory.
       $addplus="+";
       $anyname=$addplus.$anyname;
PHP (and a Little MySQL) for the Default Library Techie




                             Replacing Strings

        Use str_replace() to replace one string with
        another.

    $string= str_replace("find this", "replace with
    this", $in_ this_string);
PHP (and a Little MySQL) for the Default Library Techie




                    Create Boolean String
                      str_replace() AND


  # Replace all the AND's with +'s,
  # so that SQL’s fulltext indexing
  # can understand it.
  # The spacing is important here.
  $anyname=str_replace(" and ", " +",
  $anyname);
PHP (and a Little MySQL) for the Default Library Techie




                     Create Boolean String
                        str_replace() OR


   # OR is assumed, so just pull
   # those out.
   $anyname =str_replace(" or ", " ",
   $anyname);
PHP (and a Little MySQL) for the Default Library Techie




                     Create Boolean String
                       str_replace() NOT
  # look for NOTs
  $anyname=str_replace(" not ", " -",
  $anyname);
  # Some people may put AND NOT. Since
  # we already replaced the ANDs and
  # ORs, this may look strange.

  $anyname=str_replace(" +not ", " -",
  $anyname);
PHP (and a Little MySQL) for the Default Library Techie




                                     Mysql_query()

      Where $query is the constructed SQL query:

    mysql_query($query) or die(“Message.");


      $result=mysql_query($query) or
      die("Couldn’t execute query.");
PHP (and a Little MySQL) for the Default Library Techie




                                           Exercise 5


     Open up Notepad and get to coding!
PHP (and a Little MySQL) for the Default Library Techie




                                          search.php


             • Creates connection to database
             • Alters input for safety
             • Creates SQL query
             >>Displays the results
             • Close the connection to database
PHP (and a Little MySQL) for the Default Library Techie




                             What is an Array?


                                                          An array is a variable
                                                          that holds many
                                                          different variables in
                                                          it.



            “An array of books.”
PHP (and a Little MySQL) for the Default Library Techie




                            $result is an Array

       where the results are stored.


      $result=mysql_query($query) or
      die("Couldn’t execute query.");
PHP (and a Little MySQL) for the Default Library Techie




                        Mysql_fetch_array()
        Use mysql_fetch_array() to gather the
        waiting query results row by row, then
        display them.

            $counter=0;
            while
            ($rows=mysql_fetch_array($result))
            # displaying data from results
            {
                         Display row after row here with html.
            }
PHP (and a Little MySQL) for the Default Library Techie




                            Mysql_num_rows()

    Use mysql_num_rows to get the number of matching
    results. $Numrows is the number of rows, or records,
    in the result of the query.


          $numrows=mysql_num_rows($result);
PHP (and a Little MySQL) for the Default Library Techie




                           Plan the Display
                     Write out how you want it to
                     look!
                 There are X result(s) in your search.

                 1. lastname (maidenname), firstname middlename
                    Born: birthcity, birthstate
                    Died: deathcity, deathstate
                    Obituary: <i>newspaper</i> newsdate, newsyear
PHP (and a Little MySQL) for the Default Library Techie




                 Display Results to User


       $counter=0;
       $numrows=mysql_num_rows($result);
       Print "There are $numrows result(s) in
       your search.<p>"
PHP (and a Little MySQL) for the Default Library Techie




                 Display Results to User

 while ($rows=mysql_fetch_array($result))
 # filling-in data from results
 {
 $counter=$counter+1;
 Print $counter.". ".$rows["lastname"]. " (" . $rows["maidenname"]
 ."), " . $rows["firstname"] ." " . $rows["middlename"]."<br>";
 }




            Red is HTML and the quotation marks surrounding it.
PHP (and a Little MySQL) for the Default Library Techie




                                   Review of PHP
PHP (and a Little MySQL) for the Default Library Techie




                                          search.php


             • Creates connection to database
             • Alters input for safety
             • Creates SQL query
             • Displays the results
             >>Close the connection to database
PHP (and a Little MySQL) for the Default Library Techie




                             Close Connection


                Mysql_close is the function to close the
                connection to the server.

                            mysql_close($connection);
PHP (and a Little MySQL) for the Default Library Techie




                                           Exercise 6


     Open up Notepad and get to coding!
PHP (and a Little MySQL) for the Default Library Techie




          Include Files & Require Files

   Include and require insert files (sensitive or oft-repeated code
   stored in files) into the current code. This will prove useful and
   protective once you connect to a database, as well as for other
   repeated functions.

   Include "/path/to/filename.html";

   include ("footer.txt");

   require ("start.inc");

   example17.inc
PHP (and a Little MySQL) for the Default Library Techie




          Include Files & Require Files
    The file start.inc might look like:
   <?php

   $hostaddress="phpclass.phpclass.infopeople.org";
   $username="phpclass";
   $password="infopeople";
   $database="obituaries";
   $tablename="people";

   ?>


   example17.inc
PHP (and a Little MySQL) for the Default Library Techie




         Include File Placement
   ### Define Connection Variables ###
   Require ("start.inc");


   ### Connect to Serve & Database ###
   $connection=mysql_connect($hostaddre
   ss, $myusername, $mypassword) or die
   ("Can’t connect to server.");
PHP (and a Little MySQL) for the Default Library Techie




                                      PHP Covered
                date()                                    print
                die()                                     require()
                echo                                      str_replace()
                elseif                                    strip_tags
                if … else                                 strtolower()
                include()                                 trim()
                mysql_close()                             while
                mysql_connect()                           #
                mysql_fetch_array()                       //
                mysql_num_rows()                          /* & */
                mysql_query()                             .
                                                                    19 down,
                mysql_select_db()                         
                                                                    4592 to go!
PHP (and a Little MySQL) for the Default Library Techie




                           Evaluation Time

                                      Please go to
                               infopeople.org/wseval.html
                              and complete the evaluation.


                                          Thank you!

More Related Content

Viewers also liked

Viewers also liked (8)

MySQL Views
MySQL ViewsMySQL Views
MySQL Views
 
MySQL 5.7. Tutorial - Dutch PHP Conference 2015
MySQL 5.7. Tutorial - Dutch PHP Conference 2015MySQL 5.7. Tutorial - Dutch PHP Conference 2015
MySQL 5.7. Tutorial - Dutch PHP Conference 2015
 
library management system PHP
 library management system PHP  library management system PHP
library management system PHP
 
File Upload
File UploadFile Upload
File Upload
 
MySql slides (ppt)
MySql slides (ppt)MySql slides (ppt)
MySql slides (ppt)
 
Library management system
Library management systemLibrary management system
Library management system
 
Php mysql ppt
Php mysql pptPhp mysql ppt
Php mysql ppt
 
Library Management System PPT
Library Management System PPTLibrary Management System PPT
Library Management System PPT
 

Similar to ppt

Lecture1 introduction by okello erick
Lecture1 introduction by okello erickLecture1 introduction by okello erick
Lecture1 introduction by okello erickokelloerick
 
Apache Content Technologies
Apache Content TechnologiesApache Content Technologies
Apache Content Technologiesgagravarr
 
handout_further_resources
handout_further_resourceshandout_further_resources
handout_further_resourcestutorialsruby
 
handout_further_resources
handout_further_resourceshandout_further_resources
handout_further_resourcestutorialsruby
 
Web programming
Web programmingWeb programming
Web programmingIshucs
 
6 3 tier architecture php
6 3 tier architecture php6 3 tier architecture php
6 3 tier architecture phpcefour
 
Php training in bhubaneswar
Php training in bhubaneswar Php training in bhubaneswar
Php training in bhubaneswar litbbsr
 
Php training in bhubaneswar
Php training in bhubaneswar Php training in bhubaneswar
Php training in bhubaneswar litbbsr
 
Introduction to column oriented databases in PHP
Introduction to column oriented databases in PHPIntroduction to column oriented databases in PHP
Introduction to column oriented databases in PHPZend by Rogue Wave Software
 
IntroductiontoPHP.ppt
IntroductiontoPHP.pptIntroductiontoPHP.ppt
IntroductiontoPHP.ppttruptitasol
 
IntroductiontoPHP.ppt
IntroductiontoPHP.pptIntroductiontoPHP.ppt
IntroductiontoPHP.ppttruptitasol
 
IntroductiontoPHP.ppt
IntroductiontoPHP.pptIntroductiontoPHP.ppt
IntroductiontoPHP.ppttruptitasol
 
IntroductiontoPHP.ppt
IntroductiontoPHP.pptIntroductiontoPHP.ppt
IntroductiontoPHP.ppttruptitasol
 

Similar to ppt (20)

Lecture1 introduction by okello erick
Lecture1 introduction by okello erickLecture1 introduction by okello erick
Lecture1 introduction by okello erick
 
Php reports sumit
Php reports sumitPhp reports sumit
Php reports sumit
 
Apache Content Technologies
Apache Content TechnologiesApache Content Technologies
Apache Content Technologies
 
handout_further_resources
handout_further_resourceshandout_further_resources
handout_further_resources
 
handout_further_resources
handout_further_resourceshandout_further_resources
handout_further_resources
 
Web programming
Web programmingWeb programming
Web programming
 
6 3 tier architecture php
6 3 tier architecture php6 3 tier architecture php
6 3 tier architecture php
 
Php training in bhubaneswar
Php training in bhubaneswar Php training in bhubaneswar
Php training in bhubaneswar
 
Php training in bhubaneswar
Php training in bhubaneswar Php training in bhubaneswar
Php training in bhubaneswar
 
Lamp
LampLamp
Lamp
 
Introduction to column oriented databases in PHP
Introduction to column oriented databases in PHPIntroduction to column oriented databases in PHP
Introduction to column oriented databases in PHP
 
test
testtest
test
 
IntroductiontoPHP.ppt
IntroductiontoPHP.pptIntroductiontoPHP.ppt
IntroductiontoPHP.ppt
 
ssfsd fsdf ds f
ssfsd fsdf ds fssfsd fsdf ds f
ssfsd fsdf ds f
 
IntroductiontoPHP.ppt
IntroductiontoPHP.pptIntroductiontoPHP.ppt
IntroductiontoPHP.ppt
 
IntroductiontoPHP.ppt
IntroductiontoPHP.pptIntroductiontoPHP.ppt
IntroductiontoPHP.ppt
 
IntroductiontoPHP.ppt
IntroductiontoPHP.pptIntroductiontoPHP.ppt
IntroductiontoPHP.ppt
 
test
testtest
test
 
sdfsdfsdf
sdfsdfsdfsdfsdfsdf
sdfsdfsdf
 
345345
345345345345
345345
 

More from webhostingguy

Running and Developing Tests with the Apache::Test Framework
Running and Developing Tests with the Apache::Test FrameworkRunning and Developing Tests with the Apache::Test Framework
Running and Developing Tests with the Apache::Test Frameworkwebhostingguy
 
MySQL and memcached Guide
MySQL and memcached GuideMySQL and memcached Guide
MySQL and memcached Guidewebhostingguy
 
Novell® iChain® 2.3
Novell® iChain® 2.3Novell® iChain® 2.3
Novell® iChain® 2.3webhostingguy
 
Load-balancing web servers Load-balancing web servers
Load-balancing web servers Load-balancing web serversLoad-balancing web servers Load-balancing web servers
Load-balancing web servers Load-balancing web serverswebhostingguy
 
SQL Server 2008 Consolidation
SQL Server 2008 ConsolidationSQL Server 2008 Consolidation
SQL Server 2008 Consolidationwebhostingguy
 
Master Service Agreement
Master Service AgreementMaster Service Agreement
Master Service Agreementwebhostingguy
 
PHP and MySQL PHP Written as a set of CGI binaries in C in ...
PHP and MySQL PHP Written as a set of CGI binaries in C in ...PHP and MySQL PHP Written as a set of CGI binaries in C in ...
PHP and MySQL PHP Written as a set of CGI binaries in C in ...webhostingguy
 
Dell Reference Architecture Guide Deploying Microsoft® SQL ...
Dell Reference Architecture Guide Deploying Microsoft® SQL ...Dell Reference Architecture Guide Deploying Microsoft® SQL ...
Dell Reference Architecture Guide Deploying Microsoft® SQL ...webhostingguy
 
Managing Diverse IT Infrastructure
Managing Diverse IT InfrastructureManaging Diverse IT Infrastructure
Managing Diverse IT Infrastructurewebhostingguy
 
Web design for business.ppt
Web design for business.pptWeb design for business.ppt
Web design for business.pptwebhostingguy
 
IT Power Management Strategy
IT Power Management Strategy IT Power Management Strategy
IT Power Management Strategy webhostingguy
 
Excel and SQL Quick Tricks for Merchandisers
Excel and SQL Quick Tricks for MerchandisersExcel and SQL Quick Tricks for Merchandisers
Excel and SQL Quick Tricks for Merchandiserswebhostingguy
 
Parallels Hosting Products
Parallels Hosting ProductsParallels Hosting Products
Parallels Hosting Productswebhostingguy
 
Microsoft PowerPoint presentation 2.175 Mb
Microsoft PowerPoint presentation 2.175 MbMicrosoft PowerPoint presentation 2.175 Mb
Microsoft PowerPoint presentation 2.175 Mbwebhostingguy
 
Installation of MySQL 5.1 Cluster Software on the Solaris 10 ...
Installation of MySQL 5.1 Cluster Software on the Solaris 10 ...Installation of MySQL 5.1 Cluster Software on the Solaris 10 ...
Installation of MySQL 5.1 Cluster Software on the Solaris 10 ...webhostingguy
 

More from webhostingguy (20)

Running and Developing Tests with the Apache::Test Framework
Running and Developing Tests with the Apache::Test FrameworkRunning and Developing Tests with the Apache::Test Framework
Running and Developing Tests with the Apache::Test Framework
 
MySQL and memcached Guide
MySQL and memcached GuideMySQL and memcached Guide
MySQL and memcached Guide
 
Novell® iChain® 2.3
Novell® iChain® 2.3Novell® iChain® 2.3
Novell® iChain® 2.3
 
Load-balancing web servers Load-balancing web servers
Load-balancing web servers Load-balancing web serversLoad-balancing web servers Load-balancing web servers
Load-balancing web servers Load-balancing web servers
 
SQL Server 2008 Consolidation
SQL Server 2008 ConsolidationSQL Server 2008 Consolidation
SQL Server 2008 Consolidation
 
What is mod_perl?
What is mod_perl?What is mod_perl?
What is mod_perl?
 
What is mod_perl?
What is mod_perl?What is mod_perl?
What is mod_perl?
 
Master Service Agreement
Master Service AgreementMaster Service Agreement
Master Service Agreement
 
Notes8
Notes8Notes8
Notes8
 
PHP and MySQL PHP Written as a set of CGI binaries in C in ...
PHP and MySQL PHP Written as a set of CGI binaries in C in ...PHP and MySQL PHP Written as a set of CGI binaries in C in ...
PHP and MySQL PHP Written as a set of CGI binaries in C in ...
 
Dell Reference Architecture Guide Deploying Microsoft® SQL ...
Dell Reference Architecture Guide Deploying Microsoft® SQL ...Dell Reference Architecture Guide Deploying Microsoft® SQL ...
Dell Reference Architecture Guide Deploying Microsoft® SQL ...
 
Managing Diverse IT Infrastructure
Managing Diverse IT InfrastructureManaging Diverse IT Infrastructure
Managing Diverse IT Infrastructure
 
Web design for business.ppt
Web design for business.pptWeb design for business.ppt
Web design for business.ppt
 
IT Power Management Strategy
IT Power Management Strategy IT Power Management Strategy
IT Power Management Strategy
 
Excel and SQL Quick Tricks for Merchandisers
Excel and SQL Quick Tricks for MerchandisersExcel and SQL Quick Tricks for Merchandisers
Excel and SQL Quick Tricks for Merchandisers
 
OLUG_xen.ppt
OLUG_xen.pptOLUG_xen.ppt
OLUG_xen.ppt
 
Parallels Hosting Products
Parallels Hosting ProductsParallels Hosting Products
Parallels Hosting Products
 
Microsoft PowerPoint presentation 2.175 Mb
Microsoft PowerPoint presentation 2.175 MbMicrosoft PowerPoint presentation 2.175 Mb
Microsoft PowerPoint presentation 2.175 Mb
 
Reseller's Guide
Reseller's GuideReseller's Guide
Reseller's Guide
 
Installation of MySQL 5.1 Cluster Software on the Solaris 10 ...
Installation of MySQL 5.1 Cluster Software on the Solaris 10 ...Installation of MySQL 5.1 Cluster Software on the Solaris 10 ...
Installation of MySQL 5.1 Cluster Software on the Solaris 10 ...
 

ppt

  • 1. PHP (and a little MySQL) for the Default Library Techie Lisa Bartle, Reference Librarian Cal. State University, San Bernardino LBartle@csusb.edu 909-537-7552 An Infopeople Workshop PHP (and a Little MySQL) for the Default Library Techie Summer 2006 - This material has been created by Lisa Bartle for the Infopeople Project [infopeople.org], supported by the U.S. Institute of Museum and Library Services under the provisions of the Library Services and Technology Act, administered in California by the State Librarian. Any use of this material should credit the author and funding source.
  • 2. Introductions •Lab assistant •Participants –Name –Position –What you hope to do with PHP
  • 3. PHP (and a Little MySQL) for the Default Library Techie Assumptions for This Class 1. You know html code (e.g., tables, forms). 2. You understand the basics of databases (e.g., fields, records, truncation). 3. A little programming experience in any language is useful for this class but not essential (for example, you know what a variable is).
  • 4. PHP (and a Little MySQL) for the Default Library Techie Goals for This Class 1. Not to teach everything about PHP, but provide the basic knowledge for an online database. 2. Explain just the code, not setting up a server. 3. Provide a solid grounding so the books are not as formidable.
  • 5. PHP (and a Little MySQL) for the Default Library Techie Diagram of Web Applications Borrowed from MySQL/PHP Database Applications, 2nd ed. by Brad Bulger, Jay Greenspan, and David Wall.
  • 6. PHP (and a Little MySQL) for the Default Library Techie What is PHP? A scripting language most suitable for online database management.
  • 7. PHP (and a Little MySQL) for the Default Library Techie PHP Benefits • Open source, so it’s free • Hosting is inexpensive • PHP can be embedded in html files using .php file extension • Easy to learn • Works powerfully and intimately with MySQL and the web
  • 8. PHP (and a Little MySQL) for the Default Library Techie PHP More Benefits •Works well with Apache – also open source •Parse complex strings •Communicate with many credit card processing systems •Communicate with many protocols, including IMAP & POP3 (email), NNTP (usenet), and DNS (hostnames & addresses) •Native database support for over 25 db products including dBase, FilePro, FrontBase, IBM DB2, Hyperwave, mSQL, MySQL, Sybase, Unix dbm, Access, and many others oAccess may be more difficult to connect
  • 9. PHP (and a Little MySQL) for the Default Library Techie Who’s Using PHP? Go to http://www.php.net/usage.php to find current usage statistics. http://www.abc-lit.com
  • 10. PHP (and a Little MySQL) for the Default Library Techie Recommendations for Text Editors • EditPlus2 from ES-Computing (free) • NoteTab Light from Fookes Software (free) • PHP Designer from MP Software (free) • Crimson Editor from Ingyu Kang (free)
  • 11. PHP (and a Little MySQL) for the Default Library Techie It All Starts with the Database The MySQL Connection
  • 12. PHP (and a Little MySQL) for the Default Library Techie What is MySQL? • A database system often used for web- accessible databases • A relational database management system (RDMS), like Microsoft’s Access, using SQL
  • 13. PHP (and a Little MySQL) for the Default Library Techie MySQL Introduction • Pronounced “My Ess Que Ell,” according to the MySQL reference manual. • Can handle small databases or very large ones (ex. 50 million records, 60,000 tables and about 5,000,000,000 rows; maximum table size is 65536 terabytes, but operating systems have limitations). Look at the MySQL reference manual (downloads.mysql.com/docs/refman-5.0-en.pdf).
  • 14. PHP (and a Little MySQL) for the Default Library Techie MySQL Benefits • Open source, so it’s free • Designed to work intimately with PHP and the web • Dependable code back to 1980s and fully backward compatible • Can operate with a variety of operating systems: o Unix; FreeBSD; Mac OS X; Solaris; Windows 9x, Me, NT, 2000, XP, and Server 2003 (Microsoft products are not the best with MySQL)
  • 15. PHP (and a Little MySQL) for the Default Library Techie How Is Your Data Stored? • Access • Excel • Something else
  • 16. PHP (and a Little MySQL) for the Default Library Techie If You Have Data … • Using Access or Excel you may want to convert to MySQL using an online converter • Intelligent Converters has several for-fee programs at http://www.convert-in.com
  • 17. PHP (and a Little MySQL) for the Default Library Techie If You Don’t Have Data … • Create a database using MySQL client
  • 18. PHP (and a Little MySQL) for the Default Library Techie More If You Don’t Have Data … • Create a database using Access or Excel • Create a database using phpMyAdmin o a tool written in PHP for the administration of a MySQL server over the Web o often included with the operating system
  • 19. PHP (and a Little MySQL) for the Default Library Techie phpMyAdmin Table Creation
  • 20. PHP (and a Little MySQL) for the Default Library Techie To Maintain Your Data • Use Access or Excel to update, then convert to MySQL using a converter
  • 21. PHP (and a Little MySQL) for the Default Library Techie MySQL data INSERT INTO 'people' VALUES('Joann', 'M', 'Aardappel', "", 'Pine Bluff', 'AR', 'Fontana', 'CA', 'San Bernardino County Sun', '2000-10-09'); INSERT INTO 'people' VALUES('Louie', 'R', 'Aboytes', "", 'Mesa', 'AZ', 'Loma Linda', 'CA', 'San Bernardino County Sun', '2001-01-05'); INSERT INTO 'people' VALUES('Edith', "", 'Abramson', 'Gimble', 'St. Paul', 'MN', 'Redlands', 'CA', 'San Bernardino County Sun', '2000-11-18'); INSERT INTO 'people' VALUES('Antonia', "", 'Acevedo', 'Bermudez', "", 'Mexico', 'Fontana', 'CA', 'San Bernardino County Sun', '2000-11-14');
  • 22. PHP (and a Little MySQL) for the Default Library Techie To Maintain Your Data • Use Access or Excel to update, then convert to MySQL using a converter • Use phpMyAdmin to update
  • 23. PHP (and a Little MySQL) for the Default Library Techie phpMyAdmin Data Input
  • 24. PHP (and a Little MySQL) for the Default Library Techie Housekeeping 1. Open Internet Explorer 2. Go to Tools > Internet Options > Advanced 3. Put an X next to: Enable folder view for FTP sites
  • 25. PHP (and a Little MySQL) for the Default Library Techie Our Project Go to http://phpclass.infopeople.org/search.html
  • 26. PHP (and a Little MySQL) for the Default Library Techie The PHP Connection
  • 27. PHP (and a Little MySQL) for the Default Library Techie PHP Start and Stop •PHP code starts <?php •PPH code ends ?> example1.php
  • 28. PHP (and a Little MySQL) for the Default Library Techie Comments • Explain the purpose of the coding • Help you and others read the code • Help you when you’ve forgotten what it all means
  • 29. PHP (and a Little MySQL) for the Default Library Techie Comment Structure // begin each line inside the PHP code # begin each line inside the PHP code /* begin and */ end several lines inside the PHP code
  • 30. PHP (and a Little MySQL) for the Default Library Techie Comment Examples <?php //Purpose: to create a form for patrons’ questions ?> ---------------------------- <?php ###### Show Results to User ###### ?> ---------------------------- <?php /* Purpose: to create a form for patrons’ questions Author: Lisa Bartle Date: Nov. 6, 2006 */ ?>
  • 31. PHP (and a Little MySQL) for the Default Library Techie Exercise 1 Open up Notepad and get to coding!
  • 32. PHP (and a Little MySQL) for the Default Library Techie “Hello_Librarians”: First PHP Example <h2>Infopeople PHP class</h2> Code <?php print "<p>Hello librarians!"; ?> User Sees example1.php
  • 33. PHP (and a Little MySQL) for the Default Library Techie PHP and HTML •HTML can be outside of PHP coding •HTML can be inside of the code, but must be inside quotation marks with a print statement •PHP statements end in a semi-colon example1.php
  • 34. PHP (and a Little MySQL) for the Default Library Techie Outputting Data •Echo -- a language construct or structure for a single argument. •Print -- a language construct, which can have multiple arguments and more complex expressions. We will use PRINT in this class.
  • 35. PHP (and a Little MySQL) for the Default Library Techie Echo & Print Example <?php Code Echo "Infopeople PHP Presentation"; Print "<P>Hello librarians."; ?> User Sees example2.php
  • 36. PHP (and a Little MySQL) for the Default Library Techie What is a Variable? • A variable is a place to store information. • Information stored in a variable can be defined by the programmer. • Information stored in a variable can come from a user using a form.
  • 37. PHP (and a Little MySQL) for the Default Library Techie Variables • A variable always begins with a $ then the variable name. • Variables are case sensitive and alpha-numeric. • Do not start a variable with a number. • All the variables below are different. $book $amount $Amount $AmoUnT $AMOUNT
  • 38. PHP (and a Little MySQL) for the Default Library Techie Variable Example <?php Print "<h2>Infopeople PHP Presentation </h2><br>"; print "<p>Hello librarians! <br>"; $date="Nov. 6, 2006"; print "Today’s date is $date"; ?> example3.php
  • 39. PHP (and a Little MySQL) for the Default Library Techie Printing Variables <?php $date="Nov. 6, 2006"; print "Today’s date is $date"; Print "Today’s date is "; print $date; ?> example3.php
  • 40. PHP (and a Little MySQL) for the Default Library Techie Date Function • Use date() to display the date and time • Can display in multiple ways Jul. 12, 2006 July 12, 2006 7/12/2006 2006/07/12 example7.php
  • 41. PHP (and a Little MySQL) for the Default Library Techie Date Display $datedisplay=date("Y/m/d"); print $datedisplay; # If the date is November 6, 2005 # It would display as 2005/11/06 $showdate=date("l, F j, Y"); print $showdate; # If the date is November 6, 2005 # It would display as # Sunday, November 6, 2005 See handout “Displaying the Date Using example7.php Date()”
  • 42. PHP (and a Little MySQL) for the Default Library Techie Exercise 2 Open up Notepad and get to coding!
  • 43. PHP (and a Little MySQL) for the Default Library Techie Profession Example profession.php
  • 44. PHP (and a Little MySQL) for the Default Library Techie The HTML Connection
  • 45. PHP (and a Little MySQL) for the Default Library Techie Forms Forms provide an interface for users to query your database.
  • 46. PHP (and a Little MySQL) for the Default Library Techie Forms HTML <-- form tag goes before the form objects --> <form> [form objects go here] [radio buttons, pull-down menus, text boxes] [submit button, cancel button] </form>
  • 47. PHP (and a Little MySQL) for the Default Library Techie Radio Buttons <INPUT type="radio" name="sex" value="M"> Male<BR> <INPUT type="radio" name="sex" value="F"> Female<BR> Name becomes the variable name. Value is what the variable is holding. example9.html
  • 48. PHP (and a Little MySQL) for the Default Library Techie Pull-Down Menus <p>City of death: <select name="deathcity" size="1"> <option selected value="">Search all cities in database</option> <option value="Fontana">Fontana</option> <option value="Loma Linda">Loma Linda</option> <option value="Redlands">Redlands</option> <option value="San Bernardino">San Bernardino</option> <option value="Victorville">Victorville</option> </select> Name =variable name. Value =what variable is holding. example10.html
  • 49. PHP (and a Little MySQL) for the Default Library Techie Text Boxes <input TYPE= "text" NAME="anyname" SIZE="20" MAXLENGTH="40"> Name =variable name. example11.html
  • 50. PHP (and a Little MySQL) for the Default Library Techie Check Boxes Libraries should get more<p> <input TYPE="checkbox" NAME="money" VALUE="Yes" checked> Money <br> <input TYPE="checkbox" NAME="respect" VALUE="Yes"> Respect Name=variable name Value=what variable is holding. example13.html
  • 51. PHP (and a Little MySQL) for the Default Library Techie Submit/Reset Buttons <input TYPE="submit" NAME="Search" VALUE="Search it!"> <input TYPE="reset" NAME="Cancel" VALUE="Clear Form"> example14.html
  • 52. PHP (and a Little MySQL) for the Default Library Techie Form Action <-- not just form tag, but form action --> <form action="file,URL,or path" method="post"> [form objects here] </form>
  • 53. PHP (and a Little MySQL) for the Default Library Techie The PHP Connection
  • 54. PHP (and a Little MySQL) for the Default Library Techie Operators • Arithmetic operators • Assignment operators • Comparison operators See handout “Operators.”
  • 55. PHP (and a Little MySQL) for the Default Library Techie Arithmetic Operators $a + $b //addition $a - $b //subtraction $a * $b //multiplication $a / $b //division example6.php
  • 56. PHP (and a Little MySQL) for the Default Library Techie Assignment & Arithmetic Operators <?php $a=15; $b=30; $total=$a+$b; Print $total; Print "<p><h1> $total </h1>"; //total is 45 ?> example6.php
  • 57. PHP (and a Little MySQL) for the Default Library Techie Comparison Operators Equal $a == $b Not Equal $a != $b $a <> $b Less Than $a < $b Less Than or Equal to $a <= $b Greater Than $a > $b Greater Than or Equal to $a >= $b See handout “Operators”
  • 58. PHP (and a Little MySQL) for the Default Library Techie Difference Between = and == = Assigns a value to a variable == Checks the value of a variable See handout “Operators.”
  • 59. PHP (and a Little MySQL) for the Default Library Techie If … Else If (condition) { If ($user=="Lisa") Statement; { Print "Hello Lisa."; } } Else Else { Print "You aren't Lisa."; { } Statement; } No THEN in PHP
  • 60. PHP (and a Little MySQL) for the Default Library Techie If (condition) ElseIf { Statement; If ($user=="Lisa") { } Print "Hello Lisa."; Elseif (condition) } Elseif ($user=="Mo") { { Statement; Print "Hello Mo."; } } Else Else { { Print "Who are you?"; Statement; } }
  • 61. PHP (and a Little MySQL) for the Default Library Techie While Loops <?php $count=0; While ($count<5) While (condition) { { Print "Hello Lisa."; $count=$count + 1; Statement; } } #Another way to say #to say that is #$count++; ?> example8.php
  • 62. PHP (and a Little MySQL) for the Default Library Techie Profession Example 1. Go to http://phpclass.infopeople.org/lisa/profession.php profession.php
  • 63. PHP (and a Little MySQL) for the Default Library Techie Questions to Think About 1. What is the first step for this code? 2. What kind of php structures will be necessary? example15.php
  • 64. PHP (and a Little MySQL) for the Default Library Techie Exercise 3
  • 65. PHP (and a Little MySQL) for the Default Library Techie Top Errors & Messages 1. Missing semi-colon. 2. Misspelled variables and missing $. 3. Incomplete pairs for quotation marks, parentheses, curly brackets, etc. See handout “Common PHP Mistakes and Error Messages”
  • 66. PHP (and a Little MySQL) for the Default Library Techie Our Sample Database • This class’s prepared database is called obituaries. • The file is obituaries.sql. • It is an index of people’s names who have had obits listed in the newspaper. It is for patron’s genealogical research. • The table called people has our data. Records: 100 Fields: 11 See handout “Organize Your Database and Server Information”
  • 67. PHP (and a Little MySQL) for the Default Library Techie Download Search.html to Your Directory Go to http://phpclass.infopeople.org/search.html 1. Click View > Source 2. Save the file as search.html to your desktop. 3. Copy the file from your desktop into your directory. You will not need to create the search form from scratch.
  • 68. PHP (and a Little MySQL) for the Default Library Techie search.php >>Creates connection to server & database •Alters input for safety •Creates SQL query •Displays the results >>Close the connection to database
  • 69. PHP (and a Little MySQL) for the Default Library Techie Connect to the Server Mysql_connect() is the function used to connect to the server. mysql_connect("hostaddress", "myusername", "mypassword") or die ("message"); Die() is a function for an output message and to terminate the current script.
  • 70. PHP (and a Little MySQL) for the Default Library Techie Mysql_connect() Structure $connection=mysql_connect("hostaddress", "myusername", "mypassword") or die ("message");
  • 71. PHP (and a Little MySQL) for the Default Library Techie Mysql_connect() Example # Create connection to database # Define variables $hostaddress="phpclass.phpclass. infopeople.org"; $myusername="phpclass"; $mypassword="infopeople"; $connection=mysql_connect($hostaddress , $myusername, $mypassword) or die ("Can’t connect to server.");
  • 72. PHP (and a Little MySQL) for the Default Library Techie Close Connection Mysql_close() is the function to close the connection to the server. mysql_close($connection);
  • 73. PHP (and a Little MySQL) for the Default Library Techie Connect to the Database Mysql_select_db() is the function to select your MySQL database. mysql_select_db("database") or die ("Message");
  • 74. PHP (and a Little MySQL) for the Default Library Techie Mysql_select_db() #$database="obituaries"; #$tablename="people"; $result=mysql_select_db($database) or die("Database could not be selected");
  • 75. PHP (and a Little MySQL) for the Default Library Techie Alter Input for Safety • Creates connection to database >>Alters input for safety • Creates SQL query • Displays the results • Close the connection to database
  • 76. PHP (and a Little MySQL) for the Default Library Techie Trim(), Strip_tags(), Strtolower() • Trim removes whitespace at the beginning and end of a string. • Strip_tags tries to remove PHP & HTML tags from a string. • Strtolower converts alpha characters to lowercase. $anyname=trim($anyname); $anyname=strip_tags($anyname); $anyname=strtolower($anyname); search.php
  • 77. PHP (and a Little MySQL) for the Default Library Techie Exercise 4 Open up Notepad and get to coding!
  • 78. PHP (and a Little MySQL) for the Default Library Techie Create SQL Query • Creates connection to database • Alters input for safety >>Creates SQL query • Displays the results • Close the connection to database
  • 79. PHP (and a Little MySQL) for the Default Library Techie Concatenation “A union by chaining or linking together.” Use a period to link together strings. <?php $string1="Hello"; $string2="Librarians"; $string3=$string1." ".$string2; Print $string3; print "<p>"; Print $string1." ".$string2; ?> example5.php
  • 80. PHP (and a Little MySQL) for the Default Library Techie Escaping the Character If the string has a set of double quotation marks that must remain visible, use the [backslash] <?php before the quotation $heading=""Lisa's Books""; marks so PHP does Print $heading; not act on them and ?> only displays them. example16.php
  • 81. PHP (and a Little MySQL) for the Default Library Techie The SQL Connection
  • 82. PHP (and a Little MySQL) for the Default Library Techie Diagram of Web Applications Borrowed from MySQL/PHP Database Applications, 2nd ed. by Brad Bulger, Jay Greenspan, and David Wall.
  • 83. PHP (and a Little MySQL) for the Default Library Techie What is SQL? • Structured Query Language • A database access language standard • All SQL-capable databases support a common subset of SQL o Access, MySQL, some Oracle databases, etc.
  • 84. PHP (and a Little MySQL) for the Default Library Techie SQL Select Query Template SELECT [field],[field] from [table] WHERE [field] [operator] [parameter or input] ORDER BY [field] [ASC or DESC];
  • 85. PHP (and a Little MySQL) for the Default Library Techie SQL Query Examples Database: obituaries Table: people Fields: lastname, firstname, middlename, maidenname, newsdate, newsyear •SELECT lastname, firstname from people where newsyear > 2000; •SELECT lastname, firstname from people where newsyear > 2000 and newsyear < 2003; •SELECT lastname, firstname from people where newsyear BETWEEN 2000 and 2003; Numbers do not need quotation marks in
  • 86. PHP (and a Little MySQL) for the Default Library Techie SQL Query Examples Database: obituaries Table: people Fields: lastname, firstname, middlename, maidenname, newsdate, newsyear •SELECT * from people where lastname = "Jones"; •SELECT * from people where lastname LIKE "Jones%"; •SELECT * from people where lastname LIKE "%Jones"; •SELECT * from people where lastname LIKE "%Jones%" ORDER BY lastname ASC, firstname ASC; Text needs quotation marks in SQL.
  • 87. PHP (and a Little MySQL) for the Default Library Techie PHP & SQL in the Query SELECT * from people where lastname LIKE "%Jones%" ORDER BY lastname ASC; $query="SELECT * from people where lastname LIKE "%Jones%" ORDER BY lastname ASC";
  • 88. PHP (and a Little MySQL) for the Default Library Techie Variables in the PHP/SQL Query $query="SELECT * from people where lastname LIKE "%Jones%" ORDER BY lastname ASC"; $query="SELECT * from " .$tablename. " where lastname LIKE "%" .$anyname. "%" ORDER BY lastname ASC";
  • 89. PHP (and a Little MySQL) for the Default Library Techie Match Against In Boolean Mode $query="SELECT * from " .$tablename. " WHERE MATCH(firstname, middlename, lastname, maidenname) AGAINST ('$anyname' IN BOOLEAN MODE) AND newsyear>= " .$newsyear1. " AND newsyear<=" .$newsyear2. " ORDER BY lastname ASC"; Red=PHP Purple=SQL
  • 90. PHP (and a Little MySQL) for the Default Library Techie SQL Troubleshooting Tips Build the SQL statement slowly, piece by piece. # Keep what is working and comment it out so # that you can start from success when you # need to start over. # $query="SELECT * from ".$tablename; # This works $query="SELECT * from ".$tablename; Print the query so you can tell where it is breaking down. Print $query;
  • 91. PHP (and a Little MySQL) for the Default Library Techie SQL Query If ($deathcity=="") {$deathcityquery=" ";} else {$deathcityquery=" and deathcity="".$deathcity.""";}
  • 92. PHP (and a Little MySQL) for the Default Library Techie More SQL Query If ($anyname=="") { $query="SELECT * from " . $tablename. " WHERE newsyear >=".$newsyear1." AND newsyear<=".$newsyear2.$deathcityquery." ORDER BY lastname ASC"; } else { $query="SELECT * from " . $tablename. " WHERE match(firstname, middlename, lastname, maidenname) against ('$anyname' in boolean mode) and newsyear >=".$newsyear1." AND newsyear<=".$newsyear2.$deathcityquery." ORDER BY lastname ASC"; • }
  • 93. PHP (and a Little MySQL) for the Default Library Techie Download sql_query.php Sql_query.php is available in the main directory of the ftp server. • Copy the file to your desktop. • Open it. • Copy the query and place it under the header Create SQL Query.
  • 94. PHP (and a Little MySQL) for the Default Library Techie True Boolean Queries We have a textbox, $anyname, in our obituary search form. We want it to be Boolean searchable. Such as: (peek or byrd) and (mary or ellen) How do we do it?
  • 95. PHP (and a Little MySQL) for the Default Library Techie Alter the Input for SQL Think of our old AltaVista searches: +alice –wonderland +columbia We need to use PHP to substitute the AND, OR, NOT that the users input so that SQL can understand it.
  • 96. PHP (and a Little MySQL) for the Default Library Techie Create Boolean String # Insert an initial plus-sign so # the first term or phrase is # included as a mandatory. $addplus="+"; $anyname=$addplus.$anyname;
  • 97. PHP (and a Little MySQL) for the Default Library Techie Replacing Strings Use str_replace() to replace one string with another. $string= str_replace("find this", "replace with this", $in_ this_string);
  • 98. PHP (and a Little MySQL) for the Default Library Techie Create Boolean String str_replace() AND # Replace all the AND's with +'s, # so that SQL’s fulltext indexing # can understand it. # The spacing is important here. $anyname=str_replace(" and ", " +", $anyname);
  • 99. PHP (and a Little MySQL) for the Default Library Techie Create Boolean String str_replace() OR # OR is assumed, so just pull # those out. $anyname =str_replace(" or ", " ", $anyname);
  • 100. PHP (and a Little MySQL) for the Default Library Techie Create Boolean String str_replace() NOT # look for NOTs $anyname=str_replace(" not ", " -", $anyname); # Some people may put AND NOT. Since # we already replaced the ANDs and # ORs, this may look strange. $anyname=str_replace(" +not ", " -", $anyname);
  • 101. PHP (and a Little MySQL) for the Default Library Techie Mysql_query() Where $query is the constructed SQL query: mysql_query($query) or die(“Message."); $result=mysql_query($query) or die("Couldn’t execute query.");
  • 102. PHP (and a Little MySQL) for the Default Library Techie Exercise 5 Open up Notepad and get to coding!
  • 103. PHP (and a Little MySQL) for the Default Library Techie search.php • Creates connection to database • Alters input for safety • Creates SQL query >>Displays the results • Close the connection to database
  • 104. PHP (and a Little MySQL) for the Default Library Techie What is an Array? An array is a variable that holds many different variables in it. “An array of books.”
  • 105. PHP (and a Little MySQL) for the Default Library Techie $result is an Array where the results are stored. $result=mysql_query($query) or die("Couldn’t execute query.");
  • 106. PHP (and a Little MySQL) for the Default Library Techie Mysql_fetch_array() Use mysql_fetch_array() to gather the waiting query results row by row, then display them. $counter=0; while ($rows=mysql_fetch_array($result)) # displaying data from results { Display row after row here with html. }
  • 107. PHP (and a Little MySQL) for the Default Library Techie Mysql_num_rows() Use mysql_num_rows to get the number of matching results. $Numrows is the number of rows, or records, in the result of the query. $numrows=mysql_num_rows($result);
  • 108. PHP (and a Little MySQL) for the Default Library Techie Plan the Display Write out how you want it to look! There are X result(s) in your search. 1. lastname (maidenname), firstname middlename Born: birthcity, birthstate Died: deathcity, deathstate Obituary: <i>newspaper</i> newsdate, newsyear
  • 109. PHP (and a Little MySQL) for the Default Library Techie Display Results to User $counter=0; $numrows=mysql_num_rows($result); Print "There are $numrows result(s) in your search.<p>"
  • 110. PHP (and a Little MySQL) for the Default Library Techie Display Results to User while ($rows=mysql_fetch_array($result)) # filling-in data from results { $counter=$counter+1; Print $counter.". ".$rows["lastname"]. " (" . $rows["maidenname"] ."), " . $rows["firstname"] ." " . $rows["middlename"]."<br>"; } Red is HTML and the quotation marks surrounding it.
  • 111. PHP (and a Little MySQL) for the Default Library Techie Review of PHP
  • 112. PHP (and a Little MySQL) for the Default Library Techie search.php • Creates connection to database • Alters input for safety • Creates SQL query • Displays the results >>Close the connection to database
  • 113. PHP (and a Little MySQL) for the Default Library Techie Close Connection Mysql_close is the function to close the connection to the server. mysql_close($connection);
  • 114. PHP (and a Little MySQL) for the Default Library Techie Exercise 6 Open up Notepad and get to coding!
  • 115. PHP (and a Little MySQL) for the Default Library Techie Include Files & Require Files Include and require insert files (sensitive or oft-repeated code stored in files) into the current code. This will prove useful and protective once you connect to a database, as well as for other repeated functions. Include "/path/to/filename.html"; include ("footer.txt"); require ("start.inc"); example17.inc
  • 116. PHP (and a Little MySQL) for the Default Library Techie Include Files & Require Files The file start.inc might look like: <?php $hostaddress="phpclass.phpclass.infopeople.org"; $username="phpclass"; $password="infopeople"; $database="obituaries"; $tablename="people"; ?> example17.inc
  • 117. PHP (and a Little MySQL) for the Default Library Techie Include File Placement ### Define Connection Variables ### Require ("start.inc"); ### Connect to Serve & Database ### $connection=mysql_connect($hostaddre ss, $myusername, $mypassword) or die ("Can’t connect to server.");
  • 118. PHP (and a Little MySQL) for the Default Library Techie PHP Covered date() print die() require() echo str_replace() elseif strip_tags if … else strtolower() include() trim() mysql_close() while mysql_connect() # mysql_fetch_array() // mysql_num_rows() /* & */ mysql_query() . 19 down, mysql_select_db() 4592 to go!
  • 119. PHP (and a Little MySQL) for the Default Library Techie Evaluation Time Please go to infopeople.org/wseval.html and complete the evaluation. Thank you!