PHP (and a little MySQL) for the Default Library Techie 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. Lisa Bartle, Reference Librarian Cal. State University, San Bernardino [email protected]909-537-7552 An Infopeople Workshop
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
PHP (and a little MySQL) for the Default Library Techie
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. 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
PHP (and a Little MySQL) for the Default Library Techie
Borrowed from MySQL/PHP Database Applications, 2nd ed. by Brad Bulger, Jay Greenspan, and David Wall.
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
•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
PHP More Benefits
Who’s Using PHP?
PHP (and a Little MySQL) for the Default Library Techie
Go to http://www.php.net/usage.php to find current usage statistics.
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 phpMyAdmino 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
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');
MySQL data
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
PHP (and a Little MySQL) for the Default Library Techie
Go to http://phpclass.infopeople.org/search.html
The PHP Connection
PHP (and a Little MySQL) for the Default Library Techie
•PHP code starts <?php
•PPH code ends ?>
PHP Start and Stop
example1.php
PHP (and a Little MySQL) for the Default Library Techie
Comments
PHP (and a Little MySQL) for the Default Library Techie
• Explain the purpose of the coding
• Help you and others read the code
• Help you when you’ve forgotten what it all means
Comment Structure
PHP (and a Little MySQL) for the Default Library Techie
// begin each line inside the PHP code
# begin each line inside the PHP code
/* begin and */ end several lines inside the PHP code
Comment Examples
PHP (and a Little MySQL) for the Default Library Techie
<?php//Purpose: to create a form for patrons’ questions?>----------------------------<?php###### Show Results to User ######?>----------------------------<?php/*Purpose: to create a form for patrons’ questionsAuthor: Lisa BartleDate: Nov. 6, 2006*/?>
Exercise 1
PHP (and a Little MySQL) for the Default Library Techie
Open up Notepad and get to coding!
“Hello_Librarians”:First PHP Example
example1.php
PHP (and a Little MySQL) for the Default Library Techie
PHP (and a Little MySQL) for the Default Library Techie
If the string has a set of double quotation marks that must remain visible, use the \ [backslash] before the quotation marks so PHP does not act on them and only displays them.
example16.php
The SQL Connection
PHP (and a Little MySQL) for the Default Library Techie
Diagram of Web Applications
PHP (and a Little MySQL) for the Default Library Techie
Borrowed from MySQL/PHP Database Applications, 2nd ed. by Brad Bulger, Jay Greenspan, and David Wall.
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
•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;
PHP (and a Little MySQL) for the Default Library Techie
Database: obituaries
Table: people
Fields: lastname, firstname, middlename,
maidenname, newsdate, newsyear
Numbers do not need quotation marks in SQL.
•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;
PHP (and a Little MySQL) for the Default Library Techie
SQL Query ExamplesDatabase: obituaries
Table: people
Fields: lastname, firstname, middlename,
maidenname, newsdate, newsyear
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";
Match Against In Boolean Mode
PHP (and a Little MySQL) for the Default Library Techie
$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
SQL Troubleshooting Tips
PHP (and a Little MySQL) for the Default Library Techie
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;
If ($deathcity=="") {$deathcityquery=" ";}
else {$deathcityquery=" and deathcity=\"".$deathcity."\"";}
PHP (and a Little MySQL) for the Default Library Techie
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
More SQL Query
Download sql_query.php
PHP (and a Little MySQL) for the Default Library Techie
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.
True Boolean Queries
(peek or byrd) and (mary or ellen)
PHP (and a Little MySQL) for the Default Library Techie
How do we do it?
We have a textbox, $anyname, in our obituary search form. We want it to be Boolean searchable. Such as:
Alter the Input for SQL
PHP (and a Little MySQL) for the Default Library Techie
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.
Create Boolean String
PHP (and a Little MySQL) for the Default Library Techie
# 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);
# 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 Stringstr_replace() AND
PHP (and a Little MySQL) for the Default Library Techie
Create Boolean Stringstr_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 Stringstr_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);
Mysql_query()
PHP (and a Little MySQL) for the Default Library Techie
$result=mysql_query($query) or die("Couldn’t execute query.");
mysql_query($query) or die(“Message.");
Where $query is the constructed SQL query:
Exercise 5
PHP (and a Little MySQL) for the Default Library Techie
Open up Notepad and get to coding!
search.php
PHP (and a Little MySQL) for the Default Library Techie
• Creates connection to database
• Alters input for safety
• Creates SQL query
>>Displays the results
• Close the connection to database
What is an Array?
PHP (and a Little MySQL) for the Default Library Techie
An array is a variable that holds many different variables in it.
PHP (and a Little MySQL) for the Default Library Techie
Write out how you want it to look!
$counter=0;$numrows=mysql_num_rows($result);Print "There are $numrows result(s) in your search.<p>"
Display Results to User
PHP (and a Little MySQL) for the Default Library Techie
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>";}
Display Results to User
PHP (and a Little MySQL) for the Default Library Techie
Red is HTML and the quotation marks surrounding it.
Review of PHP
PHP (and a Little MySQL) for the Default Library Techie
search.php
PHP (and a Little MySQL) for the Default Library Techie
• Creates connection to database
• Alters input for safety
• Creates SQL query
• Displays the results
>>Close the connection to database
mysql_close($connection);
Close Connection
PHP (and a Little MySQL) for the Default Library Techie
Mysql_close is the function to close the connection to the server.
Exercise 6
PHP (and a Little MySQL) for the Default Library Techie
Open up Notepad and get to coding!
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.
PHP (and a Little MySQL) for the Default Library Techie
example17.inc
Include "/path/to/filename.html";
include ("footer.txt");
require ("start.inc");
Include Files & Require Files
PHP (and a Little MySQL) for the Default Library Techie