├── 9781430231141.jpg ├── LICENSE.txt ├── README.md ├── README.txt ├── ch01 - Introducing PHP └── validstatements.php ├── ch02 - Configuring Your Environment └── phpinfo.php ├── ch03 - PHP Basics ├── aspstyle.php ├── break.php ├── continue.php ├── converttofloat.php ├── defaultsyntax.php ├── define.php ├── dowhile.php ├── echo.php ├── for.php ├── foreach.php ├── foreach2.php ├── globalvariables.php ├── heredoc.php ├── if.php ├── ifelse.php ├── ifelseif.php ├── isname.php ├── localvariables.php ├── multiplecodeblocks.php ├── multiplelinecomments.php ├── printf.php ├── printf2.php ├── shellstylecomments.php ├── shortcircuitsyntax.php ├── shorttags.php ├── singlelinecomments.php ├── sprintf.php ├── staticvariables.php ├── superglobalvariables.php └── while.php ├── ch04 - Functions ├── creatingfunction.php ├── defaultargumentvalues.php ├── invokefunction.php ├── optionalarguments.php ├── passargumentsbyreference.php ├── passargumentsbyvalue.php ├── recursivefunctions.php └── returnmultiplevalues.php ├── ch05 - Arrays ├── Thumbs.db ├── array-count-values.php ├── array_chunk.php ├── array_combine.php ├── array_diff.php ├── array_diff_assoc.php ├── array_intersect.php ├── array_intersect_assoc.php ├── array_merge.php ├── array_merge_recursive.php ├── array_multisort.php ├── array_rand.php ├── array_slice.php ├── array_splice.php ├── array_sum.php ├── arrayflip.php ├── arrayreverse-preserve.php ├── arrayreverse.php ├── arrayunique.php ├── arsort.php ├── count.php ├── key.php ├── listing5-1.html ├── output_array.php ├── rsort.php ├── shuffle.php ├── sort.php ├── submitdata.php └── usort.php ├── ch06 - Object-Oriented PHP ├── book.php ├── destructors.php ├── invoking-parent-constructors.php ├── listing6-1.php └── static-class-members.php ├── ch07 - Advanced OOP Features ├── late_static_binding.php ├── listing7-1.php ├── listing7-2.php ├── listing7-3.php ├── listing7-4.php ├── listing7-5.php ├── listing7-6.php └── listing7-7.php ├── ch08 - Errors and Exception Handling ├── listing8-1.php ├── listing8-2.php └── listing8-3.php ├── ch09 - Strings and Regular Expressions ├── count_chars.php ├── curly-offset-syntax.php ├── ereg-2.php ├── ereg.php ├── ereg_replace-2.php ├── ereg_replace.php ├── eregi.php ├── explode.php ├── get_html_translation_table-2.php ├── get_html_translation_table.php ├── htmlentities.php ├── htmlspecialchars.php ├── implode.php ├── nl2br.php ├── parse_str.php ├── pear-validate_us.php ├── preg_grep.php ├── preg_match.php ├── preg_match_all.php ├── preg_quote.php ├── preg_replace-2.php ├── preg_replace.php ├── preg_replace_callback.php ├── preg_split.php ├── split.php ├── sql_regcase.php ├── str_pad-2.php ├── str_pad.php ├── str_replace.php ├── str_word_count-2.php ├── str_word_count.php ├── strcasecmp.php ├── strcmp.php ├── strcspn.php ├── strip_tags-2.php ├── strip_tags.php ├── strlen.php ├── strpos.php ├── strrpos.php ├── strspn.php ├── strstr.php ├── strtok.php ├── strtolower.php ├── strtoupper.php ├── strtr.php ├── substr-2.php ├── substr-3.php ├── substr.php ├── substr_count.php ├── substr_replace.php ├── ucfirst.php └── ucwords.php ├── ch10 - Working with the File and Operating System ├── basename.php ├── dirname.php ├── disk_free_space.php ├── disk_total_space.php ├── feof.php ├── fgetcsv.php ├── fgets.php ├── fgetss.php ├── file.php ├── file_get_contents.php ├── fileatime.php ├── filectime.php ├── filegroup.php ├── filemtime.php ├── fileowner.php ├── fileperms.php ├── filesize.php ├── fread.php ├── fscanf.php ├── fwrite.php ├── listing10-1.php ├── listing10-2.php ├── pathinfo.php ├── readdir.php ├── readfile.php ├── realpath.php ├── scandir.php ├── socsecurity.txt ├── symlink.php └── users.txt ├── ch11 - PEAR └── pear-numbers_roman.php ├── ch12 - Date and Time ├── adddays.php ├── addmonths.php ├── addweeks.php ├── addyears.php ├── calculate-number-days-from-date.php ├── checkdate.php ├── getarray.php ├── getdayofyear.php ├── getisoweekofyear.php ├── getlastmod.php ├── gettimeofday.php ├── getweekday.php ├── getweekofyear.php ├── isleap.php ├── mktime.php ├── number-days-any-month.php ├── number-days-current-month.php ├── setFirstDow.php ├── setLastDow.php ├── setToLastMonthDay.php ├── strftime.php ├── subdays.php ├── submonths.php ├── subweeks.php └── subyears.php ├── ch13 - Forms ├── create_dropdown.php ├── javascript.html ├── listing13-1.php ├── logins.sql ├── multivalue-forms.php ├── simpleexample.php └── subscribe.php ├── ch14 - Authenticating Your Users ├── authenticationFile.txt ├── listing14-1.php ├── listing14-10.php ├── listing14-11.php ├── listing14-2.php ├── listing14-4.php ├── listing14-6.php ├── listing14-7.php ├── listing14-8.php └── listing14-9.php ├── ch15 - Handling File Uploads ├── listing15-1.php ├── listing15-2.php ├── listing15-3.php ├── uploadmanager.html └── uploadmanager.php ├── ch16 - Networking ├── checkdnsrr-2.php ├── checkdnsrr.php ├── dnsgetrecord-2.php ├── dnsgetrecord.php ├── fsockopen.php ├── getmxrr.php ├── getservbyname.php ├── getservbyport.php ├── listing16-1.php ├── listing16-2.php ├── listing16-3.php ├── listing16-4.php ├── pear-htmlMimeMail-attachment.php ├── pingserver.php ├── portscanner.php ├── send-email-multiple-recipients-2.php ├── send-email-with-headers.php ├── send-html-email.php ├── send-mail-multiple-recipients.php ├── send-plaintext-email.php └── userbandwidth.php ├── ch17 - PHP and LDAP ├── ldap_add.php ├── ldap_bind.php ├── ldap_compare.php ├── ldap_connect.php ├── ldap_count_entries.php ├── ldap_dn2ufn.php ├── ldap_explode_dn.php ├── ldap_first_attribute.php ├── ldap_first_entry.php ├── ldap_free_result.php ├── ldap_get_attributes.php ├── ldap_get_dn.php ├── ldap_get_entries.php ├── ldap_get_values.php ├── ldap_next_attribute.php ├── ldap_next_entry.php ├── ldap_read.php ├── ldap_sort.php ├── ldap_start_tls.php └── ldap_unbind.php ├── ch18 - Session Handlers ├── create_session_variable.php ├── delete_session_variable.php ├── listing18-1.php ├── listing18-1.sql ├── listing18-2.php ├── listing18-3.html ├── recent_view_documents.php ├── session_decode.php ├── session_id.php └── sessioninfo.sql ├── ch19 - Templating with Smarty ├── listing19-1.tpl ├── listing19-2.php ├── listing19-3.php ├── listing19-4.php ├── modify-smarty-dirs.php └── multiple-caches-per-template.php ├── ch20 - Web Services ├── blog.xml └── listing20-2.php ├── ch21 - Secure PHP Programming ├── mcrypt_encrypt.php ├── md5.php └── mhash.php ├── ch22 - AJAX ├── listing22-1.php ├── listing22-2.php └── listing22-3.php ├── ch23 - Building Web Sites for the World ├── listing23_1.php ├── setlocale.php └── strftime.php ├── ch24 - MVC and the Zend Framework ├── ContactsController.php └── contacts.sql ├── ch25 - Introducing MySQL └── README.txt ├── ch26 - Installing and Configuring MySQL └── README.txt ├── ch27 - The Many MySQL Clients └── README.txt ├── ch28 - MySQL Storage Engines and Datatypes └── README.txt ├── ch29 - Securing MySQL └── README.txt ├── ch30 - Using PHP with MySQL ├── listing30_1.php ├── listing30_2.php ├── prepared_statement.php ├── products.sql ├── recuperate_memory.php └── retrieving_data.php ├── ch31 - Introducing PDO ├── bindcolumn.php ├── bindparam.php ├── columncount.php ├── execute.php ├── fetch.php ├── fetchall.php ├── fetchcolumn.php ├── products.sql └── query.php ├── ch32 - Stored Routines ├── calculate_bonus.sp ├── get_employees.sp ├── iterate.sp ├── listing32_1.php ├── listing32_2.php ├── retrieve_multiple_rows.php ├── service_info.sp └── while.php ├── ch33 - MySQL Triggers ├── helpdesk.trigger └── listing33_1.php ├── ch34 - MySQL Views ├── employee_contact_info.view ├── employee_contact_info_v2.view ├── employees.sql └── execute_view_in_php.php ├── ch35 - Practical Database Queries ├── calculate_bonus.sql ├── cursor.php ├── listing35-1.php ├── listing35-2.php ├── member_to_vehicle.sql ├── products.sql ├── sales.sql ├── subquery.php └── vehicles.sql ├── ch36 - Indexes and Searching ├── bookmarks.sql ├── bookmarks_fulltext.sql ├── bookmarks_v2.sql ├── bookmarks_v3.sql ├── bookmarks_v4.sql ├── employees.sql ├── employees_v2.sql ├── employees_v3.sql ├── listing36_3.php ├── searchextended.php └── simplesearch.php ├── ch37 - Transactions ├── customers.sql ├── listing37_1.php ├── participants.sql └── trunks.php ├── ch38 - Importing and Exporting Data ├── load_table_data_with_php.php └── sales1.sql └── contributing.md /9781430231141.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/beg-php-mysql/b3333435500a236b3c0e9d7a526b039abb506ebd/9781430231141.jpg -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/beg-php-mysql/b3333435500a236b3c0e9d7a526b039abb506ebd/LICENSE.txt -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Apress Source Code 2 | 3 | This repository accompanies [*Beginning PHP and MySQL*](http://www.apress.com/9781430231141) by W Jason Gilmore (Apress, 2010). 4 | 5 | ![Cover image](9781430231141.jpg) 6 | 7 | Download the files as a zip using the green button, or clone the repository to your machine using Git. 8 | 9 | ## Releases 10 | 11 | Release v1.0 corresponds to the code in the published book, without corrections or updates. 12 | 13 | ## Contributions 14 | 15 | See the file Contributing.md for more information on how you can contribute to this repository. 16 | -------------------------------------------------------------------------------- /README.txt: -------------------------------------------------------------------------------- 1 | Dear Reader, 2 | 3 | I'd like to thank you for purchasing the book. You've traded hard-earned money for it, and therefore I hope it serves as a valuable reference far into the future. 4 | 5 | Enclosed in this zip file are the code examples for "Beginning PHP and MySQL: From Novice to Professional, Fourth Edition". While I've tried to enclose longer listings using listing numbers within the material, making them easy to locate in this package, I realize you may also want to experiment with many of the shorter examples too. Therefore I've included those as well, using a filename that will hopefully help you quickly locate the desired example. 6 | 7 | While this code package is intended to ease the tedium and potential for error by providing you with the code found in the book, do not presume all of the examples are going to work out of the box! You may need to change pathnames, SQL parameters, and various other items before certain listings will execute properly. 8 | 9 | ===== 10 | Support 11 | ===== 12 | I'm happy to answer any book-related questions. Please e-mail me at jason@wjgilmore.com and I'll likely respond within 24 hours. 13 | 14 | ===== 15 | Errata 16 | ===== 17 | Although perfection is my goal, errors will no doubt creep into the material. If you encounter a mistake, please do let me know about it by e-mailing the information to jason@wjgilmore.com. 18 | 19 | ===== 20 | E-book 21 | ===== 22 | An electronic version of this book is available for 50% off of the list price via the Apress.com website. If you're in need of a means for quickly searching the material, consider purchasing buy a copy! 23 | 24 | Best of luck, and have fun! 25 | 26 | Jason 27 | 28 | W. Jason Gilmore 29 | http://www.wjgilmore.com/ 30 | -------------------------------------------------------------------------------- /ch01 - Introducing PHP/validstatements.php: -------------------------------------------------------------------------------- 1 | 6 | -------------------------------------------------------------------------------- /ch02 - Configuring Your Environment/phpinfo.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch03 - PHP Basics/aspstyle.php: -------------------------------------------------------------------------------- 1 | <% 2 | print "This is another PHP example."; 3 | %> -------------------------------------------------------------------------------- /ch03 - PHP Basics/break.php: -------------------------------------------------------------------------------- 1 | Non-prime number encountered: $randomNumber

"; 9 | } 10 | } 11 | ?> -------------------------------------------------------------------------------- /ch03 - PHP Basics/continue.php: -------------------------------------------------------------------------------- 1 | "; 6 | } 7 | ?> -------------------------------------------------------------------------------- /ch03 - PHP Basics/converttofloat.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch03 - PHP Basics/defaultsyntax.php: -------------------------------------------------------------------------------- 1 |

Welcome!

2 | Some dynamic output here.

"; 4 | ?> 5 |

Some static information found here...

6 | -------------------------------------------------------------------------------- /ch03 - PHP Basics/define.php: -------------------------------------------------------------------------------- 1 | "; 6 | $pi2 = 2 * PI; 7 | print "Pi doubled equals $pi2."; 8 | 9 | 10 | ?> -------------------------------------------------------------------------------- /ch03 - PHP Basics/dowhile.php: -------------------------------------------------------------------------------- 1 | "; 5 | } while ($count < 10); 6 | ?> -------------------------------------------------------------------------------- /ch03 - PHP Basics/echo.php: -------------------------------------------------------------------------------- 1 | 6 | -------------------------------------------------------------------------------- /ch03 - PHP Basics/for.php: -------------------------------------------------------------------------------- 1 | 5) break; 5 | echo "$kilometers kilometers = ".$kilometers*0.62140. " miles.
"; 6 | } 7 | 8 | ?> -------------------------------------------------------------------------------- /ch03 - PHP Basics/foreach.php: -------------------------------------------------------------------------------- 1 | Online Resources:
"; 4 | foreach($links as $link) { 5 | echo "$link
"; 6 | } 7 | ?> 8 | 9 | -------------------------------------------------------------------------------- /ch03 - PHP Basics/foreach2.php: -------------------------------------------------------------------------------- 1 | "www.apache.org", 4 | "Apress" => "www.apress.com", 5 | "The PHP Scripting Language" => "www.php.net"); 6 | 7 | 8 | echo "Online Resources:
"; 9 | foreach($links as $title => $link) { 10 | echo "$title
"; 11 | } 12 | 13 | 14 | ?> 15 | -------------------------------------------------------------------------------- /ch03 - PHP Basics/globalvariables.php: -------------------------------------------------------------------------------- 1 | 13 | -------------------------------------------------------------------------------- /ch03 - PHP Basics/heredoc.php: -------------------------------------------------------------------------------- 1 | Rome's central train station, known as Roma Termini, 5 | was built in 1867. Because it had fallen into severe disrepair in the late 20th 6 | century, the government knew that considerable resources were required to 7 | rehabilitate the station prior to the 50-year Giubileo.

8 | EXCERPT; 9 | ?> -------------------------------------------------------------------------------- /ch03 - PHP Basics/if.php: -------------------------------------------------------------------------------- 1 | Congratulations!

"; 5 | ?> 6 | -------------------------------------------------------------------------------- /ch03 - PHP Basics/ifelse.php: -------------------------------------------------------------------------------- 1 | Congratulations!!

"; 5 | } else { 6 | echo "

Sorry!

"; 7 | } 8 | ?> -------------------------------------------------------------------------------- /ch03 - PHP Basics/ifelseif.php: -------------------------------------------------------------------------------- 1 | Congratulations!

"; 6 | } elseif (abs ($_POST['guess'] - $secretNumber) < 10) { 7 | echo "

You're getting close!

"; 8 | } else { 9 | echo "

Sorry!

"; 10 | } 11 | ?> -------------------------------------------------------------------------------- /ch03 - PHP Basics/isname.php: -------------------------------------------------------------------------------- 1 | "; 4 | echo "The variable \$item is of type integer: ".is_integer($item)."
"; 5 | echo "The variable \$item is numeric: ".is_numeric($item)."
"; 6 | ?> -------------------------------------------------------------------------------- /ch03 - PHP Basics/localvariables.php: -------------------------------------------------------------------------------- 1 | ", $x); 7 | } 8 | assignx(); 9 | printf("\$x outside of function is %d
", $x); 10 | 11 | 12 | ?> 13 | -------------------------------------------------------------------------------- /ch03 - PHP Basics/multiplecodeblocks.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | <?php echo "Welcome to my We site!";?> 4 | 5 | 6 | 9 |

Today's date is

10 | 11 | 12 | -------------------------------------------------------------------------------- /ch03 - PHP Basics/multiplelinecomments.php: -------------------------------------------------------------------------------- 1 | 9 | 10 | -------------------------------------------------------------------------------- /ch03 - PHP Basics/printf.php: -------------------------------------------------------------------------------- 1 | 6 | -------------------------------------------------------------------------------- /ch03 - PHP Basics/printf2.php: -------------------------------------------------------------------------------- 1 | 6 | -------------------------------------------------------------------------------- /ch03 - PHP Basics/shellstylecomments.php: -------------------------------------------------------------------------------- 1 | 6 | 7 | -------------------------------------------------------------------------------- /ch03 - PHP Basics/shortcircuitsyntax.php: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /ch03 - PHP Basics/shorttags.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch03 - PHP Basics/singlelinecomments.php: -------------------------------------------------------------------------------- 1 | 6 | 7 | -------------------------------------------------------------------------------- /ch03 - PHP Basics/sprintf.php: -------------------------------------------------------------------------------- 1 | 8 | -------------------------------------------------------------------------------- /ch03 - PHP Basics/staticvariables.php: -------------------------------------------------------------------------------- 1 | "; 8 | } 9 | 10 | keep_track(); 11 | keep_track(); 12 | keep_track(); 13 | 14 | ?> 15 | -------------------------------------------------------------------------------- /ch03 - PHP Basics/superglobalvariables.php: -------------------------------------------------------------------------------- 1 | $value) { 4 | echo "$var => $value
"; 5 | } 6 | 7 | ?> -------------------------------------------------------------------------------- /ch03 - PHP Basics/while.php: -------------------------------------------------------------------------------- 1 | ", $count, pow($count, 2)); 5 | $count++; 6 | } 7 | ?> 8 | 9 | -------------------------------------------------------------------------------- /ch04 - Functions/creatingfunction.php: -------------------------------------------------------------------------------- 1 | Copyright © 2010 W. Jason Gilmore

"; 5 | } 6 | 7 | generate_footer(); 8 | 9 | ?> 10 | -------------------------------------------------------------------------------- /ch04 - Functions/defaultargumentvalues.php: -------------------------------------------------------------------------------- 1 | 14 | -------------------------------------------------------------------------------- /ch04 - Functions/invokefunction.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch04 - Functions/optionalarguments.php: -------------------------------------------------------------------------------- 1 | 12 | -------------------------------------------------------------------------------- /ch04 - Functions/passargumentsbyreference.php: -------------------------------------------------------------------------------- 1 | 19 | 20 | -------------------------------------------------------------------------------- /ch04 - Functions/passargumentsbyvalue.php: -------------------------------------------------------------------------------- 1 | 12 | -------------------------------------------------------------------------------- /ch04 - Functions/recursivefunctions.php: -------------------------------------------------------------------------------- 1 | %d", $pNum); 20 | printf("$%s", number_format($newBalance, 2)); 21 | printf("$%s", number_format($periodicPayment, 2)); 22 | printf("$%s", number_format($paymentPrincipal, 2)); 23 | printf("$%s", number_format($paymentInterest, 2)); 24 | 25 | # If balance not yet zero, recursively call amortizationTable() 26 | if ($newBalance > 0) { 27 | $pNum++; 28 | amortizationTable($pNum, $periodicPayment, 29 | $newBalance, $monthlyInterest); 30 | } else { 31 | return 0; 32 | } 33 | 34 | } 35 | 36 | // Loan balance 37 | $balance = 10000.00; 38 | 39 | // Loan interest rate 40 | $interestRate = .0575; 41 | 42 | // Monthly interest rate 43 | $monthlyInterest = $interestRate / 12; 44 | 45 | // Term length of the loan, in years. 46 | $termLength = 5; 47 | 48 | // Number of payments per year. 49 | $paymentsPerYear = 12; 50 | 51 | // Payment iteration 52 | $paymentNumber = 1; 53 | 54 | // Determine total number payments 55 | $totalPayments = $termLength * $paymentsPerYear; 56 | 57 | // Determine interest component of periodic payment 58 | $intCalc = 1 + $interestRate / $paymentsPerYear; 59 | 60 | // Determine periodic payment 61 | $periodicPayment = $balance * pow($intCalc,$totalPayments) * ($intCalc - 1) / 62 | (pow($intCalc,$totalPayments) - 1); 63 | 64 | // Round periodic payment to two decimals 65 | $periodicPayment = round($periodicPayment,2); 66 | 67 | // Create table 68 | echo ""; 69 | echo " 70 | 71 | 72 | "; 73 | 74 | // Call recursive function 75 | amortizationTable($paymentNumber, $periodicPayment, $balance, 76 | $monthlyInterest); 77 | 78 | // Close table 79 | echo "
Payment NumberBalancePaymentPrincipalInterest
"; 80 | 81 | ?> 82 | -------------------------------------------------------------------------------- /ch04 - Functions/returnmultiplevalues.php: -------------------------------------------------------------------------------- 1 | 13 | 14 | -------------------------------------------------------------------------------- /ch05 - Arrays/Thumbs.db: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/beg-php-mysql/b3333435500a236b3c0e9d7a526b039abb506ebd/ch05 - Arrays/Thumbs.db -------------------------------------------------------------------------------- /ch05 - Arrays/array-count-values.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch05 - Arrays/array_chunk.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch05 - Arrays/array_combine.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch05 - Arrays/array_diff.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch05 - Arrays/array_diff_assoc.php: -------------------------------------------------------------------------------- 1 | "Ohio", "CA" => "California", "HI" => "Hawaii"); 4 | $array2 = array("50" => "Hawaii", "CA" => "California", "OH" => "Ohio"); 5 | $array3 = array("TX" => "Texas", "MD" => "Maryland", "KS" => "Kansas"); 6 | $diff = array_diff_assoc($array1, $array2, $array3); 7 | print_r($diff); 8 | 9 | ?> -------------------------------------------------------------------------------- /ch05 - Arrays/array_intersect.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch05 - Arrays/array_intersect_assoc.php: -------------------------------------------------------------------------------- 1 | "Ohio", "CA" => "California", "HI" => "Hawaii"); 4 | $array2 = array("50" => "Hawaii", "CA" => "California", "OH" => "Ohio"); 5 | $array3 = array("TX" => "Texas", "MD" => "Maryland", "OH" => "Ohio"); 6 | $intersection = array_intersect_assoc($array1, $array2, $array3); 7 | print_r($intersection); 8 | 9 | ?> -------------------------------------------------------------------------------- /ch05 - Arrays/array_merge.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch05 - Arrays/array_merge_recursive.php: -------------------------------------------------------------------------------- 1 | 100, "James" => 85); 4 | $class2 = array("Micky" => 78, "John" => 45); 5 | $classScores = array_merge_recursive($class1, $class2); 6 | print_r($classScores); 7 | 8 | ?> -------------------------------------------------------------------------------- /ch05 - Arrays/array_multisort.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch05 - Arrays/array_rand.php: -------------------------------------------------------------------------------- 1 | "Columbus", "Iowa" => "Des Moines", 4 | "Arizona" => "Phoenix"); 5 | $randomStates = array_rand($states, 2); 6 | print_r($randomStates); 7 | 8 | ?> -------------------------------------------------------------------------------- /ch05 - Arrays/array_slice.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch05 - Arrays/array_splice.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch05 - Arrays/array_sum.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch05 - Arrays/arrayflip.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch05 - Arrays/arrayreverse-preserve.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch05 - Arrays/arrayreverse.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch05 - Arrays/arrayunique.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch05 - Arrays/arsort.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch05 - Arrays/count.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch05 - Arrays/key.php: -------------------------------------------------------------------------------- 1 | "Columbus", "Iowa" => "Des Moines", 4 | "Arizona" => "Phoenix"); 5 | echo "

Can you name the capitals of these states?

"; 6 | while($key = key($capitals)) { 7 | echo $key."
"; 8 | next($capitals); 9 | } 10 | 11 | ?> -------------------------------------------------------------------------------- /ch05 - Arrays/listing5-1.html: -------------------------------------------------------------------------------- 1 |
2 |

3 | Provide up to six keywords that you believe best describe the state in 4 | which you live: 5 |

6 |

Keyword 1:
7 |

8 |

Keyword 2:
9 |

10 |

Keyword 3:
11 |

12 |

Keyword 4:
13 |

14 |

Keyword 5:
15 |

16 |

Keyword 6:
17 |

18 |

19 |
-------------------------------------------------------------------------------- /ch05 - Arrays/output_array.php: -------------------------------------------------------------------------------- 1 | Name: %s
E-mail: %s
Phone: %s

", $customer); 10 | } 11 | 12 | ?> 13 | -------------------------------------------------------------------------------- /ch05 - Arrays/rsort.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch05 - Arrays/shuffle.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch05 - Arrays/sort.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch05 - Arrays/submitdata.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch05 - Arrays/usort.php: -------------------------------------------------------------------------------- 1 | $date b 27 | return ($a > $b) ? 1 : -1; 28 | } 29 | 30 | usort($dates, 'DateSort'); 31 | 32 | print_r($dates); 33 | ?> 34 | -------------------------------------------------------------------------------- /ch06 - Object-Oriented PHP/book.php: -------------------------------------------------------------------------------- 1 | setIsbn($isbn); 11 | $this->getTitle(); 12 | $this->getNumberCopies(); 13 | } 14 | 15 | public function setIsbn($isbn) 16 | { 17 | $this->isbn = $isbn; 18 | } 19 | 20 | public function getTitle() { 21 | $this->title = "Easy PHP Websites with the Zend Framework"; 22 | print "Title: ".$this->title."
"; 23 | } 24 | 25 | public function getNumberCopies() { 26 | $this->copies = "5"; 27 | print "Number copies available: ".$this->copies."
"; 28 | } 29 | } 30 | 31 | $book = new book("0615303889"); 32 | ?> 33 | -------------------------------------------------------------------------------- /ch06 - Object-Oriented PHP/destructors.php: -------------------------------------------------------------------------------- 1 | Book class instance created.

"; 11 | } 12 | 13 | function __destruct() 14 | { 15 | echo "

Book class instance destroyed.

"; 16 | } 17 | } 18 | 19 | $book = new Book("0615303889"); 20 | ?> 21 | -------------------------------------------------------------------------------- /ch06 - Object-Oriented PHP/invoking-parent-constructors.php: -------------------------------------------------------------------------------- 1 | Staff constructor called!

"; 10 | } 11 | } 12 | 13 | class Manager extends Staff 14 | { 15 | function __construct() 16 | { 17 | parent::__construct(); 18 | echo "

Manager constructor called!

"; 19 | } 20 | } 21 | 22 | $employee = new Manager(); 23 | ?> 24 | -------------------------------------------------------------------------------- /ch06 - Object-Oriented PHP/listing6-1.php: -------------------------------------------------------------------------------- 1 | name clocked in at ".date("h:i:s"); 10 | } 11 | protected function clockOut() { 12 | echo "Member $this->name clocked out at ".date("h:i:s"); 13 | } 14 | } 15 | 16 | ?> -------------------------------------------------------------------------------- /ch06 - Object-Oriented PHP/static-class-members.php: -------------------------------------------------------------------------------- 1 | "; 20 | /* Instantiate another visitors class. */ 21 | $visits2 = new visitors(); 22 | 23 | echo visitors::getVisitors()."
"; 24 | 25 | ?> -------------------------------------------------------------------------------- /ch07 - Advanced OOP Features/late_static_binding.php: -------------------------------------------------------------------------------- 1 | 21 | 22 | -------------------------------------------------------------------------------- /ch07 - Advanced OOP Features/listing7-1.php: -------------------------------------------------------------------------------- 1 | employeeid = $employeeid; 9 | } 10 | function getEmployeeID() { 11 | return $this->employeeid; 12 | } 13 | 14 | // Define a setter and getter for $tiecolor 15 | function setTiecolor($tiecolor) { 16 | $this->tiecolor = $tiecolor; 17 | } 18 | function getTiecolor() { 19 | return $this->tiecolor; 20 | } 21 | } 22 | // Create new Corporate_Drone object 23 | $drone1 = new Corporate_Drone(); 24 | 25 | // Set the $drone1 employeeid member 26 | $drone1->setEmployeeID("12345"); 27 | 28 | // Set the $drone1 tiecolor member 29 | $drone1->setTiecolor("red"); 30 | 31 | // Clone the $drone1 object 32 | $drone2 = clone $drone1; 33 | 34 | // Set the $drone2 employeeid member 35 | $drone2->setEmployeeID("67890"); 36 | 37 | // Output the $drone1 and $drone2 employeeid members 38 | echo "Drone1 employeeID: ".$drone1->getEmployeeID()."
"; 39 | echo "Drone1 tie color: ".$drone1->getTiecolor()."
"; 40 | echo "Drone2 employeeID: ".$drone2->getEmployeeID()."
"; 41 | echo "Drone2 tie color: ".$drone2->getTiecolor()."
"; 42 | ?> 43 | -------------------------------------------------------------------------------- /ch07 - Advanced OOP Features/listing7-2.php: -------------------------------------------------------------------------------- 1 | setEmployeeID("12345"); 8 | 9 | // Clone the $drone1 object 10 | $drone2 = clone $drone1; 11 | 12 | // Set the $drone2 employeeid member 13 | $drone2->setEmployeeID("67890"); 14 | 15 | // Output the $drone1 and $drone2 employeeid members 16 | echo "Drone1 employeeID: ".$drone1->getEmployeeID()."
"; 17 | echo "Drone2 employeeID: ".$drone2->getEmployeeID()."
"; 18 | echo "Drone2 tiecolor: ".$drone2->getTiecolor()."
"; 19 | 20 | 21 | ?> 22 | -------------------------------------------------------------------------------- /ch07 - Advanced OOP Features/listing7-3.php: -------------------------------------------------------------------------------- 1 | name = $name; 11 | } 12 | 13 | # Define a getter for the private $name member 14 | function getName() { 15 | return "My name is ".$this->name."
"; 16 | } 17 | } #end Employee class 18 | 19 | # Define an Executive class that inherits Employee 20 | class Executive extends Employee { 21 | # Define a method unique to Employee 22 | function pillageCompany() { 23 | echo "I'm selling company assets to finance my yacht!"; 24 | } 25 | } #end Executive class 26 | 27 | # Create a new Executive object 28 | $exec = new Executive(); 29 | 30 | # Call the setName() method, defined in the Employee class 31 | $exec->setName("Richard"); 32 | 33 | # Call the getName() method 34 | echo $exec->getName(); 35 | 36 | # Call the pillageCompany() method 37 | $exec->pillageCompany(); 38 | ?> -------------------------------------------------------------------------------- /ch07 - Advanced OOP Features/listing7-4.php: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/beg-php-mysql/b3333435500a236b3c0e9d7a526b039abb506ebd/ch07 - Advanced OOP Features/listing7-4.php -------------------------------------------------------------------------------- /ch07 - Advanced OOP Features/listing7-5.php: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/beg-php-mysql/b3333435500a236b3c0e9d7a526b039abb506ebd/ch07 - Advanced OOP Features/listing7-5.php -------------------------------------------------------------------------------- /ch07 - Advanced OOP Features/listing7-6.php: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/beg-php-mysql/b3333435500a236b3c0e9d7a526b039abb506ebd/ch07 - Advanced OOP Features/listing7-6.php -------------------------------------------------------------------------------- /ch07 - Advanced OOP Features/listing7-7.php: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/beg-php-mysql/b3333435500a236b3c0e9d7a526b039abb506ebd/ch07 - Advanced OOP Features/listing7-7.php -------------------------------------------------------------------------------- /ch08 - Errors and Exception Handling/listing8-1.php: -------------------------------------------------------------------------------- 1 | getFile().", line ". 12 | $e->getLine()."): ".$e->getMessage(); 13 | } 14 | 15 | 16 | ?> -------------------------------------------------------------------------------- /ch08 - Errors and Exception Handling/listing8-2.php: -------------------------------------------------------------------------------- 1 | language = $language; 6 | $this->errorcode = $errorcode; 7 | } 8 | 9 | function getMessageMap() { 10 | $errors = file("errors/".$this->language.".txt"); 11 | foreach($errors as $error) { 12 | list($key,$value) = explode(",",$error,2); 13 | $errorArray[$key] = $value; 14 | } 15 | return $errorArray[$this->errorcode]; 16 | } 17 | } # end MyException 18 | 19 | try { 20 | throw new MyException("english",4); 21 | } 22 | catch (MyException $e) { 23 | echo $e->getMessageMap(); 24 | } 25 | 26 | ?> -------------------------------------------------------------------------------- /ch08 - Errors and Exception Handling/listing8-3.php: -------------------------------------------------------------------------------- 1 | message = $message; 8 | $this->notifyAdmin($email); 9 | } 10 | 11 | private function notifyAdmin($email) { 12 | mail("admin@example.org","INVALID EMAIL",$email,"From:web@example.com"); 13 | } 14 | 15 | } 16 | 17 | /* The subscribe class is responsible for validating an e-mail address 18 | and adding the user e-mail address to the database. */ 19 | class subscribe { 20 | 21 | function validateEmail($email) { 22 | try { 23 | if ($email == "") { 24 | throw new Exception("You must enter an e-mail address!"); 25 | } else { 26 | list($user,$domain) = explode("@", $email); 27 | if (! checkdnsrr($domain, "MX")) 28 | { 29 | throw new InvalidEmailException("Invalid e-mail address!", $email); 30 | } else { 31 | return 1; 32 | } 33 | } 34 | } catch (Exception $e) { 35 | echo $e->getMessage(); 36 | } catch (InvalidEmailException $e) { 37 | echo $e->getMessage(); 38 | } 39 | 40 | } 41 | /* This method would presumably add the user's e-mail address to 42 | a database. */ 43 | function subscribeUser() { 44 | echo $this->email." added to the database!"; 45 | } 46 | 47 | } #end subscribe class 48 | 49 | /* Assume that the e-mail address came from a subscription form. */ 50 | 51 | $_POST['email'] = "someuser@example.com"; 52 | 53 | /* Attempt to validate and add address to database. */ 54 | if (isset($_POST['email'])) { 55 | $subscribe = new subscribe(); 56 | if($subscribe->validateEmail($_POST['email'])) 57 | $subscribe->subscribeUser($_POST['email']); 58 | } 59 | 60 | ?> -------------------------------------------------------------------------------- /ch09 - Strings and Regular Expressions/count_chars.php: -------------------------------------------------------------------------------- 1 | $frequency) 7 | echo "Character ".chr($letter)." appears $frequency times
"; 8 | ?> -------------------------------------------------------------------------------- /ch09 - Strings and Regular Expressions/curly-offset-syntax.php: -------------------------------------------------------------------------------- 1 | "; 5 | echo $thing{0}; 6 | echo $thing{1}; 7 | echo $thing{2}; 8 | ?> -------------------------------------------------------------------------------- /ch09 - Strings and Regular Expressions/ereg-2.php: -------------------------------------------------------------------------------- 1 | "; 10 | echo $regs[1]; // outputs "http://www" 11 | echo "
"; 12 | echo $regs[2]; // outputs "apress" 13 | echo "
"; 14 | echo $regs[3]; // outputs "com" 15 | ?> -------------------------------------------------------------------------------- /ch09 - Strings and Regular Expressions/ereg.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch09 - Strings and Regular Expressions/ereg_replace-2.php: -------------------------------------------------------------------------------- 1 | \\0", $url); 6 | print $url; 7 | // Displays Apress (http://www.apress.com) 8 | 9 | ?> -------------------------------------------------------------------------------- /ch09 - Strings and Regular Expressions/ereg_replace.php: -------------------------------------------------------------------------------- 1 | \\0", 4 | $text); 5 | ?> -------------------------------------------------------------------------------- /ch09 - Strings and Regular Expressions/eregi.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch09 - Strings and Regular Expressions/explode.php: -------------------------------------------------------------------------------- 1 | PHP 5's object-oriented architecture. 6 | summary; 7 | $words = sizeof(explode(' ',strip_tags($summary))); 8 | echo "Total words in summary: $words"; 9 | ?> -------------------------------------------------------------------------------- /ch09 - Strings and Regular Expressions/get_html_translation_table-2.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch09 - Strings and Regular Expressions/get_html_translation_table.php: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/beg-php-mysql/b3333435500a236b3c0e9d7a526b039abb506ebd/ch09 - Strings and Regular Expressions/get_html_translation_table.php -------------------------------------------------------------------------------- /ch09 - Strings and Regular Expressions/htmlentities.php: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/beg-php-mysql/b3333435500a236b3c0e9d7a526b039abb506ebd/ch09 - Strings and Regular Expressions/htmlentities.php -------------------------------------------------------------------------------- /ch09 - Strings and Regular Expressions/htmlspecialchars.php: -------------------------------------------------------------------------------- 1 | > of PHP!"; 3 | echo htmlspecialchars($input); 4 | ?> -------------------------------------------------------------------------------- /ch09 - Strings and Regular Expressions/implode.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch09 - Strings and Regular Expressions/nl2br.php: -------------------------------------------------------------------------------- 1 | 's. 7 | echo nl2br($recipe); 8 | ?> -------------------------------------------------------------------------------- /ch09 - Strings and Regular Expressions/parse_str.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch09 - Strings and Regular Expressions/pear-validate_us.php: -------------------------------------------------------------------------------- 1 | phoneNumber("614-999-9999"); 5 | ?> -------------------------------------------------------------------------------- /ch09 - Strings and Regular Expressions/preg_grep.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch09 - Strings and Regular Expressions/preg_match.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch09 - Strings and Regular Expressions/preg_match_all.php: -------------------------------------------------------------------------------- 1 | Zeev Suraski
Title: PHP Guru"; 3 | preg_match_all ("/(.*)<\/b>/U", $userinfo, $pat_array); 4 | print $pat_array[0][0]."
".$pat_array[0][1]."\n"; 5 | ?> -------------------------------------------------------------------------------- /ch09 - Strings and Regular Expressions/preg_quote.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch09 - Strings and Regular Expressions/preg_replace-2.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch09 - Strings and Regular Expressions/preg_replace.php: -------------------------------------------------------------------------------- 1 | \${0}", $text); 4 | ?> -------------------------------------------------------------------------------- /ch09 - Strings and Regular Expressions/preg_replace_callback.php: -------------------------------------------------------------------------------- 1 | 'World Wide Web', 7 | 'IRS' => 'Internal Revenue Service', 8 | 'PDF' => 'Portable Document Format'); 9 | if (isset($acronyms[$matches[1]])) 10 | return $matches[1] . " (" . $acronyms[$matches[1]] . ")"; 11 | else 12 | return $matches[1]; 13 | } 14 | 15 | // The target text 16 | $text = "The IRS offers tax forms in 17 | PDF format on the WWW."; 18 | // Add the acronyms' long forms to the target text 19 | $newtext = preg_replace_callback("/(.*)<\/acronym>/U", 'acronym', 20 | $text); 21 | 22 | print_r($newtext); 23 | ?> -------------------------------------------------------------------------------- /ch09 - Strings and Regular Expressions/preg_split.php: -------------------------------------------------------------------------------- 1 | "; 5 | ?> -------------------------------------------------------------------------------- /ch09 - Strings and Regular Expressions/split.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch09 - Strings and Regular Expressions/sql_regcase.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch09 - Strings and Regular Expressions/str_pad-2.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch09 - Strings and Regular Expressions/str_pad.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch09 - Strings and Regular Expressions/str_replace.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch09 - Strings and Regular Expressions/str_word_count-2.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch09 - Strings and Regular Expressions/str_word_count.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch09 - Strings and Regular Expressions/strcasecmp.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch09 - Strings and Regular Expressions/strcmp.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch09 - Strings and Regular Expressions/strcspn.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch09 - Strings and Regular Expressions/strip_tags-2.php: -------------------------------------------------------------------------------- 1 | example 3 | is awesome!"; 4 | echo strip_tags($input, ""); 5 | ?> -------------------------------------------------------------------------------- /ch09 - Strings and Regular Expressions/strip_tags.php: -------------------------------------------------------------------------------- 1 | spammer@example.com"; 3 | echo strip_tags($input); 4 | ?> -------------------------------------------------------------------------------- /ch09 - Strings and Regular Expressions/strlen.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch09 - Strings and Regular Expressions/strpos.php: -------------------------------------------------------------------------------- 1 | 23 | -------------------------------------------------------------------------------- /ch09 - Strings and Regular Expressions/strrpos.php: -------------------------------------------------------------------------------- 1 | PHP 5's object-oriented 9 | architecture. 10 | summary; 11 | 12 | if (strlen($summary) > $limit) 13 | $summary = substr($summary, 0, strrpos(substr($summary, 0, $limit), 14 | ' ')) . '...'; 15 | echo $summary; 16 | ?> -------------------------------------------------------------------------------- /ch09 - Strings and Regular Expressions/strspn.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch09 - Strings and Regular Expressions/strstr.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch09 - Strings and Regular Expressions/strtok.php: -------------------------------------------------------------------------------- 1 | "; 10 | // Don't include the first argument in subsequent calls. 11 | $tokenized = strtok($tokens); 12 | } 13 | ?> -------------------------------------------------------------------------------- /ch09 - Strings and Regular Expressions/strtolower.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch09 - Strings and Regular Expressions/strtoupper.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch09 - Strings and Regular Expressions/strtr.php: -------------------------------------------------------------------------------- 1 | " => "", "
" => ""); 3 | $html = "Today In PHP-Powered News"; 4 | echo strtr($html, $table); 5 | ?> -------------------------------------------------------------------------------- /ch09 - Strings and Regular Expressions/substr-2.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch09 - Strings and Regular Expressions/substr-3.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch09 - Strings and Regular Expressions/substr.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch09 - Strings and Regular Expressions/substr_count.php: -------------------------------------------------------------------------------- 1 | "; 10 | } 11 | ?> -------------------------------------------------------------------------------- /ch09 - Strings and Regular Expressions/substr_replace.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch09 - Strings and Regular Expressions/ucfirst.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch09 - Strings and Regular Expressions/ucwords.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch10 - Working with the File and Operating System/basename.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch10 - Working with the File and Operating System/dirname.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch10 - Working with the File and Operating System/disk_free_space.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch10 - Working with the File and Operating System/disk_total_space.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch10 - Working with the File and Operating System/feof.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch10 - Working with the File and Operating System/fgetcsv.php: -------------------------------------------------------------------------------- 1 | $name ($email) Tel. $phone

"; 5 | } 6 | ?> -------------------------------------------------------------------------------- /ch10 - Working with the File and Operating System/fgets.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch10 - Working with the File and Operating System/fgetss.php: -------------------------------------------------------------------------------- 1 |

"; 4 | 5 | /* Open the article, and read its contents. */ 6 | $fh = fopen("article.html", "rt"); 7 | 8 | while (!feof($fh)) { 9 | $article .= fgetss($fh, 1024, $tags); 10 | } 11 | fclose($fh); 12 | 13 | /* Open the file up in write mode 14 | and write $article contents. */ 15 | $fh = fopen("article.html", "wt"); 16 | fwrite($fh, $article); 17 | fclose($fh); 18 | ?> -------------------------------------------------------------------------------- /ch10 - Working with the File and Operating System/file.php: -------------------------------------------------------------------------------- 1 | $name
\n"; 10 | } 11 | ?> -------------------------------------------------------------------------------- /ch10 - Working with the File and Operating System/file_get_contents.php: -------------------------------------------------------------------------------- 1 | $name/a>
"; 8 | } 9 | ?> -------------------------------------------------------------------------------- /ch10 - Working with the File and Operating System/fileatime.php: -------------------------------------------------------------------------------- 1 | 5 | -------------------------------------------------------------------------------- /ch10 - Working with the File and Operating System/filectime.php: -------------------------------------------------------------------------------- 1 | 5 | -------------------------------------------------------------------------------- /ch10 - Working with the File and Operating System/filegroup.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch10 - Working with the File and Operating System/filemtime.php: -------------------------------------------------------------------------------- 1 | 5 | -------------------------------------------------------------------------------- /ch10 - Working with the File and Operating System/fileowner.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch10 - Working with the File and Operating System/fileperms.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch10 - Working with the File and Operating System/filesize.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch10 - Working with the File and Operating System/fread.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch10 - Working with the File and Operating System/fscanf.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch10 - Working with the File and Operating System/fwrite.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch10 - Working with the File and Operating System/listing10-1.php: -------------------------------------------------------------------------------- 1 | 37 | 38 | -------------------------------------------------------------------------------- /ch10 - Working with the File and Operating System/listing10-2.php: -------------------------------------------------------------------------------- 1 | 37 | 38 | -------------------------------------------------------------------------------- /ch10 - Working with the File and Operating System/pathinfo.php: -------------------------------------------------------------------------------- 1 | ", $pathinfo['dirname']); 4 | printf("Base name: %s
", $pathinfo['basename']); 5 | printf("Extension: %s
", $pathinfo['extension']); 6 | printf("Filename: %s
", $pathinfo['filename']); 7 | ?> 8 | 9 | -------------------------------------------------------------------------------- /ch10 - Working with the File and Operating System/readdir.php: -------------------------------------------------------------------------------- 1 | "; 5 | closedir($dh); 6 | ?> -------------------------------------------------------------------------------- /ch10 - Working with the File and Operating System/readfile.php: -------------------------------------------------------------------------------- 1 |

"; 6 | 7 | /* Open the article, and read its contents. */ 8 | $fh = fopen($file, "rt"); 9 | 10 | while (!feof($fh)) 11 | $article .= fgetss($fh, 1024, $tags); 12 | 13 | fclose($fh); 14 | 15 | /* Open the article, overwriting it with the sanitized material */ 16 | $fh = fopen($file, "wt"); 17 | fwrite($fh, $article); 18 | fclose($fh); 19 | 20 | /* Output the article to the browser. */ 21 | $bytes = readfile($file); 22 | ?> -------------------------------------------------------------------------------- /ch10 - Working with the File and Operating System/realpath.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch10 - Working with the File and Operating System/scandir.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch10 - Working with the File and Operating System/socsecurity.txt: -------------------------------------------------------------------------------- 1 | 123-45-6789 2 | 234-56-7890 3 | 345-67-8901 -------------------------------------------------------------------------------- /ch10 - Working with the File and Operating System/symlink.php: -------------------------------------------------------------------------------- 1 | 4 | -------------------------------------------------------------------------------- /ch10 - Working with the File and Operating System/users.txt: -------------------------------------------------------------------------------- 1 | Ale ale@example.com 2 | Nicole nicole@example.com 3 | Laura laura@example.com -------------------------------------------------------------------------------- /ch11 - PEAR/pear-numbers_roman.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch12 - Date and Time/adddays.php: -------------------------------------------------------------------------------- 1 | setDMY(28,4,2010); 5 | $date->addDays(5); 6 | $dcs = $date->getArray(); 7 | print_r($dcs); 8 | 9 | ?> 10 | -------------------------------------------------------------------------------- /ch12 - Date and Time/addmonths.php: -------------------------------------------------------------------------------- 1 | setDMY(28,4,2010); 5 | $date->addMonths(9); 6 | $dcs = $date->getArray(); 7 | print_r($dcs); 8 | 9 | ?> 10 | -------------------------------------------------------------------------------- /ch12 - Date and Time/addweeks.php: -------------------------------------------------------------------------------- 1 | setDMY(28,4,2010); 5 | $date->addWeeks(7); 6 | $dcs = $date->getArray(); 7 | print_r($dcs); 8 | 9 | ?> 10 | -------------------------------------------------------------------------------- /ch12 - Date and Time/addyears.php: -------------------------------------------------------------------------------- 1 | setDMY(28,4,2010); 5 | $date->addYears(4); 6 | $dcs = $date->getArray(); 7 | print_r($dcs); 8 | 9 | ?> 10 | -------------------------------------------------------------------------------- /ch12 - Date and Time/calculate-number-days-from-date.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch12 - Date and Time/checkdate.php: -------------------------------------------------------------------------------- 1 | 16 | -------------------------------------------------------------------------------- /ch12 - Date and Time/getarray.php: -------------------------------------------------------------------------------- 1 | setDMY(29,4,2010); 5 | $dcs = $date->getArray(); 6 | echo "The month: ".$dcs['month']."
"; 7 | echo "The day: ".$dcs['day']."
"; 8 | echo "The year: ".$dcs['year']."
"; 9 | 10 | ?> 11 | -------------------------------------------------------------------------------- /ch12 - Date and Time/getdayofyear.php: -------------------------------------------------------------------------------- 1 | setDMY(4,7,1776); 5 | echo $date->getDayOfYear(); 6 | 7 | ?> -------------------------------------------------------------------------------- /ch12 - Date and Time/getisoweekofyear.php: -------------------------------------------------------------------------------- 1 | setDMY(4,1,2010); 5 | echo $date->getISOWeekOfYear(); 6 | 7 | ?> 8 | -------------------------------------------------------------------------------- /ch12 - Date and Time/getlastmod.php: -------------------------------------------------------------------------------- 1 | 7 | -------------------------------------------------------------------------------- /ch12 - Date and Time/gettimeofday.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch12 - Date and Time/getweekday.php: -------------------------------------------------------------------------------- 1 | setDMY(30,4,2010); 5 | echo $date->getWeekday(); 6 | 7 | ?> 8 | -------------------------------------------------------------------------------- /ch12 - Date and Time/getweekofyear.php: -------------------------------------------------------------------------------- 1 | setDMY(4,7,1776); 5 | echo $date->getWeekOfYear(); 6 | 7 | ?> -------------------------------------------------------------------------------- /ch12 - Date and Time/isleap.php: -------------------------------------------------------------------------------- 1 | isLeap() == 1 ? "" : "not"). " a leap year."; 6 | 7 | ?> 8 | -------------------------------------------------------------------------------- /ch12 - Date and Time/mktime.php: -------------------------------------------------------------------------------- 1 | 15 | -------------------------------------------------------------------------------- /ch12 - Date and Time/number-days-any-month.php: -------------------------------------------------------------------------------- 1 | 7 | -------------------------------------------------------------------------------- /ch12 - Date and Time/number-days-current-month.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch12 - Date and Time/setFirstDow.php: -------------------------------------------------------------------------------- 1 | setDMY(28,4,2010); 5 | $date->setFirstDow(); 6 | $dcs = $date->getArray(); 7 | print_r($dcs); 8 | 9 | ?> 10 | -------------------------------------------------------------------------------- /ch12 - Date and Time/setLastDow.php: -------------------------------------------------------------------------------- 1 | setDMY(28,4,2010); 5 | $date->setLastDow(); 6 | $dcs = $date->getArray(); 7 | print_r($dcs); 8 | 9 | ?> 10 | -------------------------------------------------------------------------------- /ch12 - Date and Time/setToLastMonthDay.php: -------------------------------------------------------------------------------- 1 | setDMY(1,4,2010); 5 | $date->setToLastMonthDay(); 6 | echo $date->getDay(); 7 | 8 | ?> 9 | -------------------------------------------------------------------------------- /ch12 - Date and Time/strftime.php: -------------------------------------------------------------------------------- 1 | 8 | Numero di biglietti:
9 | Orario di partenza:
10 | Orario di ritorno:
11 | Prezzo IVA incluso:
-------------------------------------------------------------------------------- /ch12 - Date and Time/subdays.php: -------------------------------------------------------------------------------- 1 | setDMY(28,4,2010); 5 | $date->subDays(14); 6 | $dcs = $date->getArray(); 7 | print_r($dcs); 8 | 9 | ?> 10 | -------------------------------------------------------------------------------- /ch12 - Date and Time/submonths.php: -------------------------------------------------------------------------------- 1 | setDMY(28,4,2010); 5 | $date->subMonths(9); 6 | $dcs = $date->getArray(); 7 | print_r($dcs); 8 | 9 | ?> 10 | -------------------------------------------------------------------------------- /ch12 - Date and Time/subweeks.php: -------------------------------------------------------------------------------- 1 | setDMY(28,4,2010); 5 | $date->subWeeks(7); 6 | $dcs = $date->getArray(); 7 | print_r($dcs); 8 | 9 | ?> 10 | -------------------------------------------------------------------------------- /ch12 - Date and Time/subyears.php: -------------------------------------------------------------------------------- 1 | setDMY(28,4,2010); 5 | $date->subYears(2); 6 | $dcs = $date->getArray(); 7 | print_r($dcs); 8 | 9 | ?> 10 | -------------------------------------------------------------------------------- /ch13 - Forms/create_dropdown.php: -------------------------------------------------------------------------------- 1 | element and title 6 | $dropdown = ""; 16 | return $dropdown; 17 | } 18 | 19 | ?> -------------------------------------------------------------------------------- /ch13 - Forms/javascript.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | Breaking News 4 | 10 | 11 | 13 |
14 | Mail this article to a friend 15 | Article content goes here... 16 | 17 | -------------------------------------------------------------------------------- /ch13 - Forms/listing13-1.php: -------------------------------------------------------------------------------- 1 | 'Choose Language:', 8 | 'C#' => 'C#', 9 | 'JavaScript' => 'JavaScript', 10 | 'Perl' => 'Perl', 11 | 'PHP' => 'PHP' 12 | ); 13 | 14 | $form = new HTML_QuickForm2('languages', 'POST'); 15 | 16 | $fieldSet = $form->addFieldset()->setLabel('Your Developer Profile'); 17 | 18 | $name = $fieldSet->addText('name')->setLabel('Your Name:'); 19 | $name->addRule('required', 'Please provide your name.'); 20 | 21 | $email = $fieldSet->addText('email')->setLabel('Your E-mail Address:'); 22 | $email->addRule('required', 'Please provide your e-mail address.'); 23 | 24 | $language = $fieldSet->addSelect('language', null, array('options' => $languages)); 25 | $language->setLabel('Choose Your Favorite Programming Language:'); 26 | $language->addRule('required', 'Please choose a programming language.'); 27 | 28 | $fieldSet->addElement('submit', null, 'Submit!'); 29 | 30 | if ($form->validate()) { 31 | echo "

SUCCESS

"; 32 | } 33 | 34 | $renderer = HTML_QuickForm2_Renderer::factory('default') 35 | ->setOption(array('group_errors' => true)); 36 | 37 | echo $form->render($renderer); 38 | 39 | ?> 40 | 41 | -------------------------------------------------------------------------------- /ch13 - Forms/logins.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE logins ( 2 | id INTEGER UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, 3 | username VARCHAR(255) NOT NULL, 4 | pswd CHAR(32) NOT NULL 5 | ); 6 | 7 | -------------------------------------------------------------------------------- /ch13 - Forms/multivalue-forms.php: -------------------------------------------------------------------------------- 1 | "; 5 | foreach($_POST['languages'] AS $language) echo "$language
"; 6 | } 7 | ?> 8 | 9 |
10 | What's your favorite programming language?
(check all that apply):
11 | C#
12 | JavaScript
13 | Perl
14 | PHP
15 | 16 |
-------------------------------------------------------------------------------- /ch13 - Forms/simpleexample.php: -------------------------------------------------------------------------------- 1 | "; 6 | echo "The address ".$_POST['email']." will soon be a spam-magnet!
"; 7 | } 8 | ?> 9 | 10 |
11 |

12 | Name:
13 | 14 |

15 |

16 | Email Address:
17 | 18 |

19 | 20 |
-------------------------------------------------------------------------------- /ch13 - Forms/subscribe.php: -------------------------------------------------------------------------------- 1 | 2 | ", $name); 9 | printf("The address %s will soon be a spam-magnet!
", $email); 10 | } 11 | ?> 12 | 13 |
14 |

15 | Name:
16 | 17 |

18 |

19 | Email Address:
20 | 21 |

22 | 23 |
24 | 25 | -------------------------------------------------------------------------------- /ch14 - Authenticating Your Users/authenticationFile.txt: -------------------------------------------------------------------------------- 1 | jason:60d99e58d66a5e0f4f89ec3ddd1d9a80 2 | donald:d5fc4b0e45c8f9a333c0056492c191cf 3 | mickey:bc180dbc583491c00f8a1cd134f7517b 4 | 5 | -------------------------------------------------------------------------------- /ch14 - Authenticating Your Users/listing14-1.php: -------------------------------------------------------------------------------- 1 | "; 11 | echo "Your password: {$_SERVER['PHP_AUTH_PW']}
"; 12 | } 13 | ?> 14 | 15 | -------------------------------------------------------------------------------- /ch14 - Authenticating Your Users/listing14-10.php: -------------------------------------------------------------------------------- 1 | prepare("UPDATE logins SET hash=? WHERE email=?"); 13 | $stmt->bind_param('ss', $id, $address); 14 | 15 | $stmt->execute(); 16 | 17 | $email = <<< email 18 | Dear user, 19 | Click on the following link to reset your password: 20 | http://www.example.com/users/lostpassword.php?id=$id 21 | email; 22 | 23 | // Email user password reset options 24 | mail($address,"Password recovery","$email","FROM:services@example.com"); 25 | echo "

Instructions regarding resetting your password have been sent to 26 | $address

"; 27 | ?> 28 | 29 | -------------------------------------------------------------------------------- /ch14 - Authenticating Your Users/listing14-11.php: -------------------------------------------------------------------------------- 1 | prepare("UPDATE logins SET pswd=? WHERE hash=?"); 13 | $stmt->execute(); 14 | 15 | // Display the new password 16 | echo "

Your password has been reset to {$pswd}.

"; 17 | ?> 18 | 19 | -------------------------------------------------------------------------------- /ch14 - Authenticating Your Users/listing14-2.php: -------------------------------------------------------------------------------- 1 | 13 | -------------------------------------------------------------------------------- /ch14 - Authenticating Your Users/listing14-4.php: -------------------------------------------------------------------------------- 1 | 28 | 29 | -------------------------------------------------------------------------------- /ch14 - Authenticating Your Users/listing14-6.php: -------------------------------------------------------------------------------- 1 | prepare("SELECT username, pswd FROM logins 25 | WHERE username=? AND pswd=MD5(?)"); 26 | 27 | $stmt->bind_param('ss', $_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']); 28 | 29 | $stmt->execute(); 30 | 31 | $stmt->store_result(); 32 | 33 | if ($stmt->num_rows == 0) 34 | authenticate_user(); 35 | } 36 | 37 | ?> 38 | 39 | -------------------------------------------------------------------------------- /ch14 - Authenticating Your Users/listing14-7.php: -------------------------------------------------------------------------------- 1 | "mysqli://webuser:secret@localhost/chapter14", 11 | 'table' => "logins", 12 | 'usernamecol' => "username", 13 | 'passwordcol' => "pswd", 14 | 'cryptType' => "md5", 15 | 'db_fields' => "*" 16 | ); 17 | 18 | // Instantiate Auth_HTTP 19 | $auth = new Auth_HTTP("MDB2", $dblogin) or die("Can't connect!"); 20 | 21 | // Message to provide in case of authentication failure 22 | $auth->setCancelText('Authentication credentials not accepted!'); 23 | 24 | // Begin the authentication process 25 | $auth->start(); 26 | 27 | // Check for credentials. If not available, prompt for them 28 | if($auth->getAuth()) 29 | echo "Welcome, {$auth->getAuthData('username')}
"; 30 | ?> 31 | 32 | -------------------------------------------------------------------------------- /ch14 - Authenticating Your Users/listing14-8.php: -------------------------------------------------------------------------------- 1 | 18 | 19 | -------------------------------------------------------------------------------- /ch14 - Authenticating Your Users/listing14-9.php: -------------------------------------------------------------------------------- 1 | "mysql://corpweb:secret@localhost/corporate", 11 | 'table' => "userauth", 12 | 'usernamecol' => "username", 13 | 'passwordcol' => "pswd", 14 | 'cryptType' => "md5" 15 | 'db_fields' => "*" 16 | ); 17 | 18 | // Instantiate Auth_HTTP 19 | $auth = new Auth_HTTP("DB", $dblogin) or die("blah"); 20 | 21 | // Begin the authentication process 22 | $auth->start(); 23 | 24 | // Message to provide in case of authentication failure 25 | $auth->setCancelText('Authentication credentials not accepted!'); 26 | 27 | // Check for credentials. If not available, prompt for them. 28 | if($auth->getAuth()) 29 | { 30 | echo "Welcome, $auth->commonname
"; 31 | } 32 | 33 | ?> -------------------------------------------------------------------------------- /ch15 - Handling File Uploads/listing15-1.php: -------------------------------------------------------------------------------- 1 |
2 |
3 |
4 |
5 |
6 | 7 |
8 | Class notes must be uploaded in PDF format.

"; 18 | } else { 19 | // Move uploaded file to final destination. 20 | $name = $_POST['name']; 21 | $result = move_uploaded_file($_FILES['classnotes']['tmp_name'], 22 | FILEREPOSITORY.$_FILES['classnotes']['name']); 23 | if ($result == 1) echo "

File successfully uploaded.

"; 24 | else echo "

There was a problem uploading the file.

"; 25 | } 26 | } 27 | ?> 28 | 29 | -------------------------------------------------------------------------------- /ch15 - Handling File Uploads/listing15-2.php: -------------------------------------------------------------------------------- 1 | getFiles('classnotes'); 8 | 9 | // If no problems with uploaded file 10 | if ($file->isValid()) { 11 | $file->moveTo('/home/httpd/html/uploads'); 12 | echo "File successfully uploaded!"; 13 | } 14 | else { 15 | echo $file->errorMsg(); 16 | } 17 | ?> 18 | 19 | -------------------------------------------------------------------------------- /ch15 - Handling File Uploads/listing15-3.php: -------------------------------------------------------------------------------- 1 | getFiles('classnotes'); 9 | 10 | // Load the file properties to associative array 11 | $props = $file->getProp(); 12 | 13 | // Output the properties 14 | print_r($props); 15 | ?> 16 | 17 | -------------------------------------------------------------------------------- /ch15 - Handling File Uploads/uploadmanager.html: -------------------------------------------------------------------------------- 1 |
2 | Name:

3 | Email:

4 | Homework:

5 |

6 |
-------------------------------------------------------------------------------- /ch15 - Handling File Uploads/uploadmanager.php: -------------------------------------------------------------------------------- 1 | Potential script abuse attempt detected.

"; 7 | } 8 | ?> -------------------------------------------------------------------------------- /ch16 - Networking/checkdnsrr-2.php: -------------------------------------------------------------------------------- 1 | 12 | 13 | -------------------------------------------------------------------------------- /ch16 - Networking/checkdnsrr.php: -------------------------------------------------------------------------------- 1 | 8 | 9 | -------------------------------------------------------------------------------- /ch16 - Networking/dnsgetrecord-2.php: -------------------------------------------------------------------------------- 1 | 5 | 6 | -------------------------------------------------------------------------------- /ch16 - Networking/dnsgetrecord.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch16 - Networking/fsockopen.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch16 - Networking/getmxrr.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch16 - Networking/getservbyname.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch16 - Networking/getservbyport.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch16 - Networking/listing16-1.php: -------------------------------------------------------------------------------- 1 | Scan results for $target

"; 17 | 18 | // Execute the scan 19 | foreach ($range as $port) { 20 | $result = @fsockopen($target, $port,$errno,$errstr,1); 21 | if ($result) echo "

Socket open at port $port

"; 22 | } 23 | 24 | ?> 25 | 26 | -------------------------------------------------------------------------------- /ch16 - Networking/listing16-2.php: -------------------------------------------------------------------------------- 1 | 20 |

Example.com Stamp Company

21 |

22 | Dear $name,
23 | Thank you for your interest in Example.com's fine selection of 24 | collectible stamps. Please respond at your convenience with your telephone 25 | number and a suggested date and time to chat. 26 |

27 | 28 |

I look forward to hearing from you.

29 | 30 |

31 | Sincerely,
32 | Bram Brownstein
33 | President, Example.com Stamp Supply 34 | html; 35 | 36 | // Identify the Relevant Mail Headers 37 | $headers['From'] = $from; 38 | $headers['Subject'] = $subject; 39 | 40 | // Instantiate Mail_mime Class 41 | $mimemail = new Mail_mime(); 42 | 43 | // Set HTML Message 44 | $mimemail->setHTMLBody($html); 45 | 46 | // Build Message 47 | $message = $mimemail->get(); 48 | 49 | // Prepare the Headers 50 | $mailheaders = $mimemail->headers($headers); 51 | 52 | // Create New Instance of Mail Class 53 | $email =& Mail::factory('mail'); 54 | 55 | // Send the E-mail Already! 56 | $email->send($recipient, $mailheaders, $message) or die("Can't send message!"); 57 | 58 | ?> 59 | 60 | -------------------------------------------------------------------------------- /ch16 - Networking/listing16-3.php: -------------------------------------------------------------------------------- 1 |

2 |

3 | IP Address:
4 | . 5 | . 6 | . 7 | 8 |

9 | 10 |

11 | Subnet Mask:
12 | . 13 | . 14 | . 15 | 16 |

17 | 18 | 19 | 20 |
21 | 22 | "; 39 | echo "
    "; 40 | echo "
  • IP Address: ". long2ip($ip)."
  • "; 41 | echo "
  • Subnet Mask: ". long2ip($netmask)."
  • "; 42 | echo "
  • Network Address: ". long2ip($na)."
  • "; 43 | echo "
  • Broadcast Address: ". long2ip($ba)."
  • "; 44 | echo "
  • Total Available Hosts: ".($ba - $na - 1)."
  • "; 45 | echo "
  • Host Range: ". long2ip($na + 1)." - ". 46 | long2ip($ba - 1)."
  • "; 47 | echo "
"; 48 | } 49 | ?> 50 | 51 | -------------------------------------------------------------------------------- /ch16 - Networking/listing16-4.php: -------------------------------------------------------------------------------- 1 | "; 14 | 15 | // Define the stop time 16 | $stop = time(); 17 | 18 | // Calculate the time taken to send the data 19 | $duration = $stop - $start; 20 | 21 | // Divide the file size by the number of seconds taken to transmit it 22 | $speed = round($fsize / $duration,2); 23 | 24 | // Display the calculated speed in Kilobytes per second 25 | echo "Your network speed: $speed KB/sec."; 26 | 27 | ?> 28 | 29 | -------------------------------------------------------------------------------- /ch16 - Networking/pear-htmlMimeMail-attachment.php: -------------------------------------------------------------------------------- 1 | setFrom('Jason '); 8 | $mail->setReturnPath('author@example.com'); 9 | 10 | // Set the Subject 11 | $mail->setSubject('Test with attached email'); 12 | 13 | // Set the body 14 | $mail->setText("Please find attached Chapter 16. Thank you!"); 15 | 16 | // Retrieve a file for attachment 17 | $attachment = $mail->getFile('chapter16.doc'); 18 | 19 | // Attach the file, assigning it a name and a corresponding Mime-type. 20 | $mail->addAttachment($attachment, 'chapter16.doc', 'application/vnd.ms-word'); 21 | 22 | // Send the email to editor@example.com 23 | $result = $mail->send(array('editor@example.com')); 24 | 25 | 26 | ?> -------------------------------------------------------------------------------- /ch16 - Networking/pingserver.php: -------------------------------------------------------------------------------- 1 | "; 11 | system("/bin/ping -c $count $server"); 12 | echo ""; 13 | 14 | // Kill the task 15 | system("killall -q ping"); 16 | 17 | ?> -------------------------------------------------------------------------------- /ch16 - Networking/portscanner.php: -------------------------------------------------------------------------------- 1 | "; 5 | system("/usr/bin/nmap $target"); 6 | echo ""; 7 | 8 | // Kill the task 9 | system("killall -q nmap"); 10 | 11 | ?> -------------------------------------------------------------------------------- /ch16 - Networking/send-email-multiple-recipients-2.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch16 - Networking/send-email-with-headers.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch16 - Networking/send-html-email.php: -------------------------------------------------------------------------------- 1 | 11 | 12 | Your Winter Quarter Schedule 13 | 14 | 15 |

Your Winter quarter class schedule follows.
16 | Please contact your guidance counselor should you have any questions. 17 |

18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 |
ClassTeacherDaysTime
Math 630Kelly, GeorgeMWF10:30am
Physics 133Josey, JohnTR1:00pm
29 | 30 | 31 | "; 32 | 33 | // Send the message 34 | mail("student@example.com", "Wi/03 Class Schedule", $body, $headers); 35 | 36 | ?> -------------------------------------------------------------------------------- /ch16 - Networking/send-mail-multiple-recipients.php: -------------------------------------------------------------------------------- 1 | setTXTBody($txt); 35 | 36 | // Build Message 37 | $message = $mimemail->get(); 38 | 39 | // Prepare the Headers 40 | $mailheaders = $mimemail->headers($headers); 41 | 42 | // Create New Instance of Mail Class 43 | $email =& Mail::factory('mail'); 44 | 45 | // Send the E-mail! 46 | $email->send($recipient, $mailheaders, $message) or die("Can't send message!"); 47 | 48 | ?> 49 | 50 | -------------------------------------------------------------------------------- /ch16 - Networking/send-plaintext-email.php: -------------------------------------------------------------------------------- 1 | 5 | 6 | -------------------------------------------------------------------------------- /ch16 - Networking/userbandwidth.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch17 - PHP and LDAP/ldap_add.php: -------------------------------------------------------------------------------- 1 | 11 | 12 | -------------------------------------------------------------------------------- /ch17 - PHP and LDAP/ldap_bind.php: -------------------------------------------------------------------------------- 1 | 13 | 14 | -------------------------------------------------------------------------------- /ch17 - PHP and LDAP/ldap_compare.php: -------------------------------------------------------------------------------- 1 | Your phone number is up-to-date

"; 7 | } else { 8 | echo "

The entered phone number does not match our records. 9 | Perhaps you've recently moved?

" ; 10 | ?> -------------------------------------------------------------------------------- /ch17 - PHP and LDAP/ldap_connect.php: -------------------------------------------------------------------------------- 1 | 7 | 8 | -------------------------------------------------------------------------------- /ch17 - PHP and LDAP/ldap_count_entries.php: -------------------------------------------------------------------------------- 1 | $results = ldap_search($connection, $dn, "sn=G*"); 2 | $count = ldap_count_entries($connection, $results); 3 | echo "

Total entries retrieved: $count

"; 4 | 5 | -------------------------------------------------------------------------------- /ch17 - PHP and LDAP/ldap_dn2ufn.php: -------------------------------------------------------------------------------- 1 | 8 | 9 | -------------------------------------------------------------------------------- /ch17 - PHP and LDAP/ldap_explode_dn.php: -------------------------------------------------------------------------------- 1 | ", $component); 8 | 9 | ?> 10 | 11 | -------------------------------------------------------------------------------- /ch17 - PHP and LDAP/ldap_first_attribute.php: -------------------------------------------------------------------------------- 1 | $results = ldap_search($ldapconn, $dn, "sn=G*", array(telephoneNumber, mail)); 2 | $entry = ldap_first_entry($ldapconn, $results); 3 | $fAttr = ldap_first_attribute($ldapconn, $entry, $pointer); 4 | echo $fAttr; -------------------------------------------------------------------------------- /ch17 - PHP and LDAP/ldap_first_entry.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch17 - PHP and LDAP/ldap_free_result.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch17 - PHP and LDAP/ldap_get_attributes.php: -------------------------------------------------------------------------------- 1 | $dn = "OU=People,OU=facstf,DC=ad,DC=example,DC=com"; 2 | 3 | $attributes = array("sn","telephonenumber"); 4 | 5 | $filter = "memberof=CN=staff,OU=Groups,DC=ad,DC=example,DC=com"; 6 | $result = ldap_search($ad, $dn, $filter, $attributes); 7 | 8 | $entry = ldap_first_entry($ad, $result); 9 | 10 | while($entry) { 11 | 12 | $attrs = ldap_get_attributes($ad, $entry); 13 | for ($i=0; $i<$attrs["count"]; $i++) 14 | { 15 | $attrName = $attrs[$i]; 16 | $values = ldap_get_values($ad,$entry,$attrName); 17 | for ($j=0; $j < $values["count"]; $j++) 18 | { 19 | echo "$attrName: ".$values[$j]."
"; 20 | } 21 | } 22 | $entry = ldap_next_entry($ad,$entry); 23 | } -------------------------------------------------------------------------------- /ch17 - PHP and LDAP/ldap_get_dn.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch17 - PHP and LDAP/ldap_get_entries.php: -------------------------------------------------------------------------------- 1 | ", $entries[$x]["mail"][0]); 30 | } 31 | 32 | ?> 33 | 34 | -------------------------------------------------------------------------------- /ch17 - PHP and LDAP/ldap_get_values.php: -------------------------------------------------------------------------------- 1 | "; 11 | echo "Last name: ".$lastname[0]."
"; 12 | echo "Email addresses: "; 13 | 14 | $x=0; 15 | while ($x < $mail["count"]) { 16 | echo $mail[$x]. " "; 17 | $x++; 18 | } 19 | ?> -------------------------------------------------------------------------------- /ch17 - PHP and LDAP/ldap_next_attribute.php: -------------------------------------------------------------------------------- 1 | $results = ldap_search($ldapconn, $dn, "sn=G*", 2 | array(telephoneNumber, userPrincipalName, mail)); 3 | $entry = ldap_first_entry($ldapconn, $results); 4 | $attr = ldap_first_attribute($ldapconn, $entry, $ber); 5 | while ($attr = ldap_next_attribute($ldapconn, $entry, &$ber)) echo $attr."
"; -------------------------------------------------------------------------------- /ch17 - PHP and LDAP/ldap_next_entry.php: -------------------------------------------------------------------------------- 1 | "; 16 | $entry = ldap_next_entry($ldapconn, $entry); 17 | } 18 | ?> -------------------------------------------------------------------------------- /ch17 - PHP and LDAP/ldap_read.php: -------------------------------------------------------------------------------- 1 | ", $entry[0]["givenname"][0]); 26 | printf("Last name: %s
", $entry[0]["sn"][0]); 27 | 28 | // Close the connection 29 | ldap_unbind($connection); 30 | 31 | ?> 32 | 33 | -------------------------------------------------------------------------------- /ch17 - PHP and LDAP/ldap_sort.php: -------------------------------------------------------------------------------- 1 | ", 15 | $entries[$i]["givenName"][0], $entries[$i]["sn"][0]); 16 | } 17 | 18 | ldap_unbind($connection); 19 | ?> 20 | 21 | -------------------------------------------------------------------------------- /ch17 - PHP and LDAP/ldap_start_tls.php: -------------------------------------------------------------------------------- 1 | 6 | 7 | -------------------------------------------------------------------------------- /ch17 - PHP and LDAP/ldap_unbind.php: -------------------------------------------------------------------------------- 1 | 16 | 17 | -------------------------------------------------------------------------------- /ch18 - Session Handlers/create_session_variable.php: -------------------------------------------------------------------------------- 1 | 6 | 7 | -------------------------------------------------------------------------------- /ch18 - Session Handlers/delete_session_variable.php: -------------------------------------------------------------------------------- 1 | ", $_SESSION['username']); 5 | unset($_SESSION['username']); 6 | printf("Username now set to: %s", $_SESSION['username']); 7 | ?> 8 | 9 | -------------------------------------------------------------------------------- /ch18 - Session Handlers/listing18-1.php: -------------------------------------------------------------------------------- 1 | prepare("SELECT first_name FROM users WHERE username = ? and password = ?"); 15 | 16 | $stmt->bind_param('ss', $_POST['username'], $_POST['password]); 17 | 18 | $stmt->execute(); 19 | 20 | $stmt->store_result(); 21 | 22 | if ($stmt->num_rows == 1) 23 | { 24 | 25 | $stmt->bind_result($firstName); 26 | 27 | $stmt->fetch(); 28 | 29 | $_SESSION['first_name'] = $firstName; 30 | 31 | header("Location: http://www.example.com/"); 32 | 33 | } 34 | 35 | } else { 36 | require_once('login.html'); 37 | } 38 | 39 | } else { 40 | echo "You are already logged into the site."; 41 | } 42 | 43 | ?> 44 | 45 | -------------------------------------------------------------------------------- /ch18 - Session Handlers/listing18-1.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE users ( 2 | id INTEGER UNSIGNED NOT NULL AUTO_INCREMENT, 3 | first_name VARCHAR(255) NOT NULL, 4 | username VARCHAR(255) NOT NULL, 5 | password VARCHAR(32) NOT NULL, 6 | PRIMARY KEY(id) 7 | ); 8 | 9 | -------------------------------------------------------------------------------- /ch18 - Session Handlers/listing18-2.php: -------------------------------------------------------------------------------- 1 | _dbLink = new mysqli($host, $user, $pswd, $db); 14 | $this->_sessionName = $sessionName; 15 | $this->_sessionTable = $sessionTable; 16 | 17 | session_set_save_handler( 18 | array($this, "session_open"), 19 | array($this, "session_close"), 20 | array($this, "session_read"), 21 | array($this, "session_write"), 22 | array($this, "session_destroy"), 23 | array($this, "session_gc") 24 | ); 25 | 26 | session_start(); 27 | 28 | } 29 | 30 | function session_open($session_path, $session_name) { 31 | 32 | $this->_sessionName = $session_name; 33 | return true; 34 | 35 | } 36 | 37 | function session_close() { 38 | 39 | return 1; 40 | 41 | } 42 | 43 | function session_write($SID, $value) { 44 | 45 | $stmt = $this->_dbLink->prepare(" 46 | INSERT INTO {$this->_sessionTable} 47 | (sid, value) VALUES (?, ?) ON DUPLICATE KEY 48 | UPDATE value = ?, expiration = NULL"); 49 | 50 | $stmt->bind_param('sss', $SID, $value, $value); 51 | 52 | $stmt->execute(); 53 | 54 | session_write_close(); 55 | 56 | } 57 | 58 | function session_read($SID) { 59 | 60 | $stmt = $this->_dbLink->prepare( 61 | "SELECT value FROM {$this->_sessionTable} 62 | WHERE sid = ? AND 63 | UNIX_TIMESTAMP(expiration) + " . 64 | self::SESS_EXPIRE . " > UNIX_TIMESTAMP(NOW())" 65 | ); 66 | 67 | $stmt->bind_param('s', $SID); 68 | 69 | if ($stmt->execute()) 70 | { 71 | 72 | $stmt->bind_result($value); 73 | 74 | $stmt->fetch(); 75 | 76 | if (! empty($value)) 77 | { 78 | return $value; 79 | } 80 | 81 | } 82 | 83 | } 84 | 85 | public function session_destroy($SID) { 86 | 87 | $stmt = $this->_dbLink->prepare("DELETE FROM {$this->_sessionTable} WHERE SID = ?"); 88 | 89 | $stmt->bind_param('s', $SID); 90 | 91 | $stmt->execute(); 92 | 93 | } 94 | 95 | public function session_gc($lifetime) { 96 | 97 | $stmt = $this->_dbLink->prepare("DELETE FROM {$this->_sessionTable} 98 | WHERE UNIX_TIMESTAMP(expiration) < " . UNIX_TIMESTAMP(NOW()) - self::SESS_EXPIRE); 99 | 100 | $stmt->execute(); 101 | 102 | } 103 | 104 | } 105 | 106 | ?> 107 | -------------------------------------------------------------------------------- /ch18 - Session Handlers/listing18-3.html: -------------------------------------------------------------------------------- 1 |

2 |

3 | Username:

4 | Password:

5 | 6 |
7 |

8 | 9 | -------------------------------------------------------------------------------- /ch18 - Session Handlers/recent_view_documents.php: -------------------------------------------------------------------------------- 1 | prepare("SELECT id, title, content FROM articles WHERE id = ?"); 11 | 12 | $stmt->bind_param('i', $_GET['id']); 13 | 14 | $stmt->execute(); 15 | 16 | $stmt->store_result(); 17 | 18 | if ($stmt->num_rows == 1) 19 | { 20 | 21 | $stmt->bind_result($id, $title, $content); 22 | 23 | } 24 | 25 | // Add article title and link to list 26 | $articleLink = "{$title}"; 27 | 28 | if (! in_array($articleLink, $_SESSION['articles'])) 29 | $_SESSION['articles'][] = $articleLink; 30 | 31 | // Display the article 32 | echo "

$title

$content

"; 33 | 34 | // Output list of requested articles 35 | 36 | echo "

Recently Viewed Articles

"; 37 | echo "
    "; 38 | foreach($_SESSION['articles'] as $doc) { 39 | echo "
  • $doc
  • "; 40 | } 41 | echo "
"; 42 | ?> 43 | 44 | -------------------------------------------------------------------------------- /ch18 - Session Handlers/session_decode.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch18 - Session Handlers/session_id.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch18 - Session Handlers/sessioninfo.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE sessioninfo ( 2 | sid VARCHAR(255) NOT NULL, 3 | value TEXT NOT NULL, 4 | expiration TIMESTAMP NOT NULL, 5 | PRIMARY KEY(sid) 6 | ); 7 | 8 | -------------------------------------------------------------------------------- /ch19 - Templating with Smarty/listing19-1.tpl: -------------------------------------------------------------------------------- 1 | 2 | 3 | {$pagetitle} 4 | 5 | 6 | {if $name eq "Kirk"} 7 |

Welcome back Captain!

8 | {else} 9 |

Swab the decks, mate!

10 | {/if} 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /ch19 - Templating with Smarty/listing19-2.php: -------------------------------------------------------------------------------- 1 | assign("pagetitle", "Welcome to the Starship."); 10 | $smarty->assign("name", "Kirk"); 11 | 12 | // Render and display the template. 13 | $smarty->display("index.tpl"); 14 | ?> 15 | 16 | -------------------------------------------------------------------------------- /ch19 - Templating with Smarty/listing19-3.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | {$title} 4 | 5 | 6 |

7 | Hi, {$name}. Welcome to the wonderful world of Smarty. 8 |

9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /ch19 - Templating with Smarty/listing19-4.php: -------------------------------------------------------------------------------- 1 | assign("name", "Jason Gilmore"); 7 | $smarty->assign("title", "Smarty Rocks!"); 8 | 9 | // Retrieve and output the template 10 | $smarty->display("welcome.tpl"); 11 | ?> 12 | 13 | -------------------------------------------------------------------------------- /ch19 - Templating with Smarty/modify-smarty-dirs.php: -------------------------------------------------------------------------------- 1 | template_dir="/usr/local/lib/php5/smarty/template_dir/"; 8 | $smarty->compile_dir="/usr/local/lib/php5/smarty/compile_dir/"; 9 | $smarty->config_dir="/usr/local/lib/php5/smarty/config_dir/"; 10 | $smarty->cache_dir="/usr/local/lib/php5/smarty/cache_dir/"; 11 | ?> -------------------------------------------------------------------------------- /ch19 - Templating with Smarty/multiple-caches-per-template.php: -------------------------------------------------------------------------------- 1 | caching = 1; 8 | 9 | try { 10 | 11 | // If template not already cached, retrieve the appropriate information. 12 | if (!is_cached("boxerbio.tpl", $_GET['boxerid'])) { 13 | $bx = new boxer(); 14 | 15 | if (! $bx->retrieveBoxer($_GET['boxerid']) ) 16 | throw new Exception("Boxer not found."); 17 | 18 | // Create the appropriate Smarty variables 19 | $smarty->assign("name", $bx->getName()); 20 | $smarty->assign("bio", $bx->getBio()); 21 | } 22 | 23 | /* Render the template, caching it and assigning it the name 24 | * represented by $_GET['boxerid']. If already cached, then 25 | * retrieve that cached template 26 | */ 27 | $smarty->display("boxerbio.tpl", $_GET['boxerid']); 28 | 29 | } catch (Exception $e) { 30 | echo $e->getMessage(); 31 | } 32 | ?> 33 | 34 | -------------------------------------------------------------------------------- /ch20 - Web Services/blog.xml: -------------------------------------------------------------------------------- 1 | 7 | 8 | 9 | 10 | WJGilmore.com 11 | http://localhost/index.php/site/index/ 12 | 13 | en 14 | wj@wjgilmore.com 15 | 16 | Copyright 2010 17 | 2010-07-21T13:24:52+00:00 18 | 19 | 20 | 21 | E-Commerce Made Easy with FoxyCart 22 | http://www.wjgilmore.com/index.php/site/e-commerce_made_easy_with_foxycart/ 23 | 24 | ExpressionEngine, PHP 25 | 2010-07-21T13:24:52+00:00 26 | 27 | 28 | 29 | Refactor Your Web Site Database with Stored Procedures and Views 30 | http://www.wjgilmore.com/site/refactor_your_web_site_database/ 31 | 32 | PHP, Zend Framework 33 | 2010-07-20T20:24:14+00:00 34 | 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /ch20 - Web Services/listing20-2.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Pride and Prejudice 5 | Jane Austen 6 | Jane Austen's most popular work. 7 | 8 | 9 | The Conformist 10 | Alberto Moravia 11 | Alberto Moravia's classic psychological novel. 12 | 13 | 14 | The Sun Also Rises 15 | Ernest Hemingway 16 | The masterpiece that launched Hemingway's 17 | career. 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /ch21 - Secure PHP Programming/mcrypt_encrypt.php: -------------------------------------------------------------------------------- 1 | 9 | 10 | -------------------------------------------------------------------------------- /ch21 - Secure PHP Programming/md5.php: -------------------------------------------------------------------------------- 1 | 6 | 7 | -------------------------------------------------------------------------------- /ch21 - Secure PHP Programming/mhash.php: -------------------------------------------------------------------------------- 1 | 6 | -------------------------------------------------------------------------------- /ch22 - AJAX/listing22-1.php: -------------------------------------------------------------------------------- 1 |
2 | 3 |

4 | Provide Your E-mail Address
5 | 6 |

7 | 8 |

9 | Choose a Username
10 | 11 | Check Username 12 |

13 | 14 |

15 | Choose and Confirm Password
16 |
17 | 18 |

19 | 20 |

21 | 22 |

23 | 24 |
25 | 26 | -------------------------------------------------------------------------------- /ch22 - AJAX/listing22-2.php: -------------------------------------------------------------------------------- 1 | 30 | 31 | -------------------------------------------------------------------------------- /ch22 - AJAX/listing22-3.php: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 39 | 40 | -------------------------------------------------------------------------------- /ch23 - Building Web Sites for the World/listing23_1.php: -------------------------------------------------------------------------------- 1 | 15 | 16 |
17 |
18 | 19 | 20 |
21 | 22 | -------------------------------------------------------------------------------- /ch23 - Building Web Sites for the World/setlocale.php: -------------------------------------------------------------------------------- 1 | ", 5 | number_format(4532.23, 2, $locale['decimal_point'], 6 | $locale['thousands_sep'])); 7 | setlocale(LC_ALL, 'en_US'); 8 | $locale = localeconv(); 9 | printf("(en_US) Total hours spent commuting %s", 10 | number_format(4532.23, 2, $locale['decimal_point'], 11 | $locale['thousands_sep'])); 12 | ?> 13 | 14 | -------------------------------------------------------------------------------- /ch23 - Building Web Sites for the World/strftime.php: -------------------------------------------------------------------------------- 1 | 5 | -------------------------------------------------------------------------------- /ch24 - MVC and the Zend Framework/ContactsController.php: -------------------------------------------------------------------------------- 1 | select()->order('name'); 15 | $this->view->contacts = $contact->fetchAll($query); 16 | } 17 | 18 | 19 | public function addAction() 20 | { 21 | 22 | $form = new Application_Model_ContactForm( 23 | array('action' => '/contact/add', 24 | 'method' => 'POST' 25 | ) 26 | ); 27 | 28 | 29 | if ($this->getRequest()->isPost()) { 30 | 31 | if ($form->isValid($this->getRequest()->getPost())) { 32 | 33 | $contact = new Zend_Db_Table('contacts'); 34 | $data = array ( 35 | 'name' => $this->_request->getPost('name'), 36 | 'email' => $this->_request->getPost('email'), 37 | 'type' => $this->_request->getPost('type') 38 | ); 39 | 40 | $contact->insert($data); 41 | 42 | echo "

Contact added!

"; 43 | 44 | } 45 | 46 | } 47 | 48 | $this->view->form = $form; 49 | 50 | } 51 | 52 | 53 | } 54 | 55 | -------------------------------------------------------------------------------- /ch24 - MVC and the Zend Framework/contacts.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE contacts ( 2 | id INTEGER UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, 3 | name VARCHAR(100) NOT NULL, 4 | email VARCHAR(100) NOT NULL, 5 | type VARCHAR(100) NOT NULL 6 | ); 7 | 8 | -------------------------------------------------------------------------------- /ch25 - Introducing MySQL/README.txt: -------------------------------------------------------------------------------- 1 | There are no code examples found in Chapter 24. -------------------------------------------------------------------------------- /ch26 - Installing and Configuring MySQL/README.txt: -------------------------------------------------------------------------------- 1 | There are no code examples found in Chapter 26. -------------------------------------------------------------------------------- /ch27 - The Many MySQL Clients/README.txt: -------------------------------------------------------------------------------- 1 | There are no code examples found in Chapter 27. -------------------------------------------------------------------------------- /ch28 - MySQL Storage Engines and Datatypes/README.txt: -------------------------------------------------------------------------------- 1 | There are no code examples found in Chapter 28. -------------------------------------------------------------------------------- /ch29 - Securing MySQL/README.txt: -------------------------------------------------------------------------------- 1 | There are no code examples found in Chapter 27. -------------------------------------------------------------------------------- /ch30 - Using PHP with MySQL/listing30_1.php: -------------------------------------------------------------------------------- 1 | stmt_init(); 11 | 12 | // Prepare the statement for execution 13 | $stmt->prepare($query); 14 | 15 | // Bind the parameters 16 | $stmt->bind_param('ssd', $sku, $name, $price); 17 | 18 | // Assign the posted sku array 19 | $skuarray = $_POST['sku']; 20 | 21 | // Assign the posted name array 22 | $namearray = $_POST['name']; 23 | 24 | // Assign the posted price array 25 | $pricearray = $_POST['price']; 26 | 27 | // Initialize the counter 28 | $x = 0; 29 | 30 | // Cycle through the array, and iteratively execute the query 31 | while ($x < sizeof($skuarray)) { 32 | 33 | $sku = $skuarray[$x]; 34 | $name = $namearray[$x]; 35 | $price = $pricearray[$x]; 36 | 37 | $stmt->execute(); 38 | 39 | } 40 | 41 | // Recuperate the statement resources 42 | $stmt->close(); 43 | 44 | // Close the connection 45 | $mysqli->close(); 46 | 47 | ?> 48 | 49 | -------------------------------------------------------------------------------- /ch30 - Using PHP with MySQL/listing30_2.php: -------------------------------------------------------------------------------- 1 | stmt_init(); 11 | 12 | // Prepare the statement for execution 13 | $stmt->prepare($query); 14 | 15 | // Execute the statement 16 | $stmt->execute(); 17 | 18 | // Bind the result parameters 19 | $stmt->bind_result($sku, $name, $price); 20 | 21 | // Cycle through the results and output the data 22 | 23 | while($stmt->fetch()) 24 | printf("%s, %s, %s
", $sku, $name, $price); 25 | 26 | // Recuperate the statement resources 27 | $stmt->close(); 28 | 29 | // Close the connection 30 | $mysqli->close(); 31 | 32 | ?> 33 | 34 | -------------------------------------------------------------------------------- /ch30 - Using PHP with MySQL/prepared_statement.php: -------------------------------------------------------------------------------- 1 | stmt_init(); 11 | 12 | // Prepare the statement for execution 13 | $stmt->prepare($query); 14 | 15 | .. Do something with the prepared statement 16 | 17 | // Recuperate the statement resources 18 | $stmt->close(); 19 | 20 | // Close the connection 21 | $mysqli->close(); 22 | 23 | ?> 24 | 25 | -------------------------------------------------------------------------------- /ch30 - Using PHP with MySQL/products.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE products ( 2 | id INT NOT NULL AUTO_INCREMENT, 3 | sku VARCHAR(8) NOT NULL, 4 | name VARCHAR(100) NOT NULL, 5 | price DECIMAL(5,2) NOT NULL, 6 | PRIMARY KEY(id) 7 | ) 8 | 9 | -------------------------------------------------------------------------------- /ch30 - Using PHP with MySQL/recuperate_memory.php: -------------------------------------------------------------------------------- 1 | query($query); 7 | 8 | $result = $mysqli->query($query, MYSQLI_STORE_RESULT); 9 | 10 | // Iterate through the result set 11 | while(list($sku, $name, $price) = $result->fetch_row()) 12 | printf("(%s) %s: \$%s
", $sku, $name, $price); 13 | 14 | // Recuperate the query resources 15 | $result->free(); 16 | 17 | // Perhaps perform some other large query 18 | 19 | ?> 20 | 21 | -------------------------------------------------------------------------------- /ch30 - Using PHP with MySQL/retrieving_data.php: -------------------------------------------------------------------------------- 1 | query($query, MYSQLI_STORE_RESULT); 10 | 11 | // Iterate through the result set 12 | while(list($sku, $name, $price) = $result->fetch_row()) 13 | printf("(%s) %s: \$%s
", $sku, $name, $price); 14 | 15 | ?> 16 | 17 | -------------------------------------------------------------------------------- /ch31 - Introducing PDO/bindcolumn.php: -------------------------------------------------------------------------------- 1 | prepare($query); 10 | $stmt->execute(); 11 | 12 | // Bind according to column offset 13 | $stmt->bindColumn(1, $sku); 14 | 15 | // Bind according to column title 16 | $stmt->bindColumn('title', $title); 17 | 18 | // Fetch the row 19 | $row = $stmt->fetch(PDO::FETCH_BOUND); 20 | 21 | // Output the data 22 | printf("Product: %s (%s)", $title, $sku); 23 | ?> 24 | 25 | 26 | ?> 27 | -------------------------------------------------------------------------------- /ch31 - Introducing PDO/bindparam.php: -------------------------------------------------------------------------------- 1 | prepare($query); 9 | 10 | $sku = 'MN873213'; 11 | $title = 'Minty Mouthwash'; 12 | 13 | // Bind the parameters 14 | $stmt->bindParam(':sku', $sku); 15 | $stmt->bindParam(':title', $title); 16 | 17 | // Execute the query 18 | $stmt->execute(); 19 | 20 | $sku = 'AB223234'; 21 | $title = 'Lovable Lipstick'; 22 | 23 | // Bind the parameters 24 | $stmt->bindParam(':sku', $sku); 25 | $stmt->bindParam(':title', $title); 26 | 27 | // Execute again 28 | $stmt->execute(); 29 | ?> 30 | 31 | -------------------------------------------------------------------------------- /ch31 - Introducing PDO/columncount.php: -------------------------------------------------------------------------------- 1 | query($query); 6 | 7 | // Report how many columns were returned 8 | printf("There were %d product fields returned.", $result->columnCount()); 9 | 10 | ?> -------------------------------------------------------------------------------- /ch31 - Introducing PDO/execute.php: -------------------------------------------------------------------------------- 1 | prepare($query); 8 | 9 | // Execute the query 10 | $stmt->execute(array(':sku' => 'MN873213', ':title' => 'Minty Mouthwash')); 11 | 12 | // Execute again 13 | $stmt->execute(array(':sku' => 'AB223234', ':title' => 'Lovable Lipstick')); 14 | ?> 15 | -------------------------------------------------------------------------------- /ch31 - Introducing PDO/fetch.php: -------------------------------------------------------------------------------- 1 | query('SELECT sku, title FROM products ORDER BY title'); 8 | 9 | while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { 10 | $sku = $row['sku']; 11 | $title = $row['title']; 12 | printf("Product: %s (%s)
", $title, $sku); 13 | } 14 | 15 | ?> 16 | 17 | -------------------------------------------------------------------------------- /ch31 - Introducing PDO/fetchall.php: -------------------------------------------------------------------------------- 1 | query('SELECT sku, title FROM products ORDER BY title'); 5 | 6 | // Retrieve all of the rows 7 | $rows = $stmt->fetchAll(); 8 | 9 | // Output the rows 10 | foreach ($rows as $row) { 11 | $sku = $row[0]; 12 | $title = $row[1]; 13 | printf("Product: %s (%s)
", $title, $sku); 14 | } 15 | 16 | 17 | 18 | ?> 19 | -------------------------------------------------------------------------------- /ch31 - Introducing PDO/fetchcolumn.php: -------------------------------------------------------------------------------- 1 | query('SELECT sku, title FROM products ORDER BY title'); 5 | 6 | // Fetch the first row first column 7 | $sku = $result->fetchColumn(0); 8 | 9 | // Fetch the second row second column 10 | $title = $result->fetchColumn(1); 11 | 12 | // Output the data. 13 | echo "Product: $title ($sku)"; 14 | 15 | 16 | 17 | ?> 18 | -------------------------------------------------------------------------------- /ch31 - Introducing PDO/products.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE products ( 2 | id INT NOT NULL AUTO_INCREMENT, 3 | sku CHAR(8) NOT NULL, 4 | title VARCHAR(100) NOT NULL, 5 | PRIMARY KEY(id) 6 | ); 7 | 8 | -------------------------------------------------------------------------------- /ch31 - Introducing PDO/query.php: -------------------------------------------------------------------------------- 1 | $query = 'SELECT sku, title FROM products ORDER BY id'; 2 | foreach ($dbh->query($query) AS $row) { 3 | $sku = $row['sku']; 4 | $title = $row['title']; 5 | printf("Product: %s (%s)
", $title, $sku); 6 | } 7 | 8 | -------------------------------------------------------------------------------- /ch32 - Stored Routines/calculate_bonus.sp: -------------------------------------------------------------------------------- 1 | DELIMITER // 2 | CREATE FUNCTION calculate_bonus 3 | (emp_id CHAR(8)) RETURNS DECIMAL(10,2) 4 | COMMENT 'Calculate employee bonus' 5 | BEGIN 6 | DECLARE total DECIMAL(10,2); 7 | DECLARE bonus DECIMAL(10,2); 8 | SELECT SUM(revenue) INTO total FROM sales WHERE employee_id = emp_id; 9 | SET bonus = total * .05; 10 | RETURN bonus; 11 | END; 12 | // 13 | DELIMITER ; 14 | 15 | -------------------------------------------------------------------------------- /ch32 - Stored Routines/get_employees.sp: -------------------------------------------------------------------------------- 1 | CREATE PROCEDURE get_employees() 2 | SELECT employee_id, name, position FROM employees ORDER by name; 3 | -------------------------------------------------------------------------------- /ch32 - Stored Routines/iterate.sp: -------------------------------------------------------------------------------- 1 | DELIMITER // 2 | 3 | DROP PROCEDURE IF EXISTS `corporate`.`calc_bonus`// 4 | 5 | CREATE PROCEDURE `corporate`.`calc_bonus` () 6 | BEGIN 7 | 8 | DECLARE empID INT; 9 | DECLARE emp_cat INT; 10 | DECLARE sal DECIMAL(8,2); 11 | DECLARE finished INTEGER DEFAULT 0; 12 | 13 | DECLARE emp_cur CURSOR FOR 14 | SELECT employee_id, salary FROM employees ORDER BY employee_id; 15 | 16 | DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished=1; 17 | 18 | OPEN emp_cur; 19 | 20 | calcloop: LOOP 21 | 22 | FETCH emp_cur INTO empID, emp_cat, sal; 23 | 24 | IF finished=1 THEN 25 | LEAVE calcloop; 26 | END IF; 27 | 28 | IF emp_cat=0 THEN 29 | ITERATE calcloop; 30 | END IF; 31 | 32 | UPDATE employees SET salary = sal + sal * 0.05 WHERE employee_id=empID; 33 | 34 | END LOOP calcloop; 35 | 36 | CLOSE emp_cur; 37 | 38 | END// 39 | 40 | DELIMITER ; 41 | 42 | -------------------------------------------------------------------------------- /ch32 - Stored Routines/listing32_1.php: -------------------------------------------------------------------------------- 1 |
2 | Employee ID:
3 | 4 | 5 |
6 | 7 | -------------------------------------------------------------------------------- /ch32 - Stored Routines/listing32_2.php: -------------------------------------------------------------------------------- 1 | prepare("SELECT calculate_bonus(?) AS bonus"); 11 | 12 | $stmt->bind_param('s', $eid); 13 | 14 | $stmt->execute(); 15 | 16 | $stmt->bind_result($bonus); 17 | 18 | $stmt->fetch(); 19 | 20 | printf("Your bonus is \$%01.2f",$bonus); 21 | ?> 22 | 23 | -------------------------------------------------------------------------------- /ch32 - Stored Routines/retrieve_multiple_rows.php: -------------------------------------------------------------------------------- 1 | query("CALL get_employees()"); 7 | 8 | // Loop through the results 9 | while (list($employee_id, $name, $position) = $result->fetch_row()) { 10 | echo "$employee_id, $name, $position
"; 11 | } 12 | 13 | ?> 14 | 15 | -------------------------------------------------------------------------------- /ch32 - Stored Routines/service_info.sp: -------------------------------------------------------------------------------- 1 | DELIMITER // 2 | 3 | CREATE PROCEDURE service_info 4 | (IN client_id INT, IN services varchar(20)) 5 | 6 | BEGIN 7 | 8 | DECLARE comma_pos INT; 9 | DECLARE current_id INT; 10 | 11 | svcs: LOOP 12 | 13 | SET comma_pos = LOCATE(',', services); 14 | SET current_id = SUBSTR(services, 1, comma_pos); 15 | 16 | IF current_id <> 0 THEN 17 | SET services = SUBSTR(services, comma_pos+1); 18 | ELSE 19 | SET current_id = services; 20 | END IF; 21 | 22 | INSERT INTO request_info VALUES(NULL, client_id, current_id); 23 | 24 | IF comma_pos = 0 OR current_id = '' THEN 25 | LEAVE svcs; 26 | END IF; 27 | 28 | END LOOP; 29 | 30 | END// 31 | 32 | DELIMITER ; 33 | 34 | -------------------------------------------------------------------------------- /ch32 - Stored Routines/while.php: -------------------------------------------------------------------------------- 1 | DELIMITER // 2 | CREATE PROCEDURE test_data 3 | (IN rows INT) 4 | BEGIN 5 | 6 | DECLARE val1 FLOAT; 7 | DECLARE val2 FLOAT; 8 | 9 | WHILE rows > 0 DO 10 | SELECT RAND() INTO val1; 11 | SELECT RAND() INTO val2; 12 | INSERT INTO analysis VALUES(NULL, val1, val2); 13 | SET rows = rows - 1; 14 | END WHILE; 15 | 16 | END// 17 | 18 | DELIMITER ; 19 | 20 | -------------------------------------------------------------------------------- /ch33 - MySQL Triggers/helpdesk.trigger: -------------------------------------------------------------------------------- 1 | DELIMITER // 2 | CREATE TRIGGER au_reassign_ticket 3 | AFTER UPDATE ON technicians 4 | FOR EACH ROW 5 | BEGIN 6 | IF NEW.available = 0 THEN 7 | UPDATE tickets SET technician_id=0 WHERE technician_id=NEW.id; 8 | END IF; 9 | END;// 10 | 11 | -------------------------------------------------------------------------------- /ch33 - MySQL Triggers/listing33_1.php: -------------------------------------------------------------------------------- 1 | 0, 'max_range' => 1); 8 | $email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL); 9 | $available = filter_var($_POST['available'], FILTER_VALIDATE_INT, $options); 10 | 11 | // Create the UPDATE query 12 | $stmt = $mysqli->prepare("UPDATE technicians SET available=? WHERE email=?"); 13 | 14 | $stmt->bind_param('is', $available, $email); 15 | 16 | // Execute query and offer user output 17 | if ($stmt->execute()) { 18 | 19 | echo "

Thank you for updating your profile.

"; 20 | 21 | if ($available == 0) { 22 | echo "

Your tickets will be reassigned to another technician.

"; 23 | } 24 | 25 | } else { 26 | echo "

There was a problem updating your profile.

"; 27 | } 28 | 29 | ?> 30 | 31 | -------------------------------------------------------------------------------- /ch34 - MySQL Views/employee_contact_info.view: -------------------------------------------------------------------------------- 1 | CREATE VIEW employee_contact_info_view AS 2 | SELECT first_name, last_name, email, phone 3 | FROM employees ORDER BY last_name ASC; 4 | 5 | -------------------------------------------------------------------------------- /ch34 - MySQL Views/employee_contact_info_v2.view: -------------------------------------------------------------------------------- 1 | CREATE VIEW employee_contact_info_view 2 | (`First Name`, `Last Name`, `Email Address`, `Telephone`) AS 3 | SELECT first_name, last_name, email, phone 4 | FROM employees ORDER BY last_name ASC; 5 | 6 | -------------------------------------------------------------------------------- /ch34 - MySQL Views/employees.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE employees ( 2 | id INT UNSIGNED NOT NULL AUTO_INCREMENT, 3 | employee_id CHAR(8) NOT NULL, 4 | first_name VARCHAR(100) NOT NULL, 5 | last_name VARCHAR(100) NOT NULL, 6 | email VARCHAR(100) NOT NULL, 7 | phone CHAR(10) NOT NULL, 8 | salary DECIMAL(8,2) NOT NULL, 9 | PRIMARY KEY(id) 10 | ); 11 | 12 | -------------------------------------------------------------------------------- /ch34 - MySQL Views/execute_view_in_php.php: -------------------------------------------------------------------------------- 1 | query($query)) { 11 | 12 | printf(""); 13 | printf(""); 14 | 15 | // Output the headers 16 | $fields = $result->fetch_fields(); 17 | foreach ($fields as $field) 18 | printf("", $field->name); 19 | 20 | printf(""); 21 | 22 | // Output the results 23 | while ($employee = $result->fetch_row()) { 24 | 25 | $first_name = $employee[0]; 26 | $last_name = $employee[1]; 27 | $email = $employee[2]; 28 | $phone = $employee[3]; 29 | 30 | // Format the phone number 31 | $phone = ereg_replace("([0-9]{3})([0-9]{3})([0-9]{4})", 32 | "(\\1) \\2-\\3", $phone); 33 | 34 | printf(""); 35 | printf("", $first_name, $last_name); 36 | printf("", $email, $phone); 37 | printf(""); 38 | 39 | } 40 | 41 | } 42 | ?> 43 | 44 | -------------------------------------------------------------------------------- /ch35 - Practical Database Queries/calculate_bonus.sql: -------------------------------------------------------------------------------- 1 | CREATE PROCEDURE calculate_bonus() 2 | BEGIN 3 | 4 | DECLARE emp_id INT; 5 | DECLARE sal DECIMAL(8,2); 6 | DECLARE comm DECIMAL(3,2); 7 | DECLARE done INT; 8 | 9 | DECLARE calc_bonus CURSOR FOR SELECT id, salary, commission FROM employees; 10 | 11 | DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1; 12 | 13 | OPEN calc_bonus; 14 | 15 | BEGIN_calc: LOOP 16 | 17 | FETCH calc_bonus INTO emp_id, sal, comm; 18 | 19 | IF done THEN 20 | LEAVE begin_calc; 21 | END IF; 22 | 23 | IF sal > 60000.00 THEN 24 | IF comm > 0.05 THEN 25 | UPDATE employees SET bonus = sal * comm WHERE id=emp_id; 26 | ELSEIF comm <= 0.05 THEN 27 | UPDATE employees SET bonus = sal * 0.03 WHERE id=emp_id; 28 | END IF; 29 | ELSE 30 | UPDATE employees SET bonus = sal * 0.07 WHERE id=emp_id; 31 | END IF; 32 | 33 | END LOOP begin_calc; 34 | 35 | CLOSE calc_bonus; 36 | 37 | END// 38 | 39 | DELIMITER ; 40 | 41 | -------------------------------------------------------------------------------- /ch35 - Practical Database Queries/cursor.php: -------------------------------------------------------------------------------- 1 | query("CALL calculate_bonus()"); 8 | 9 | ?> 10 | 11 | -------------------------------------------------------------------------------- /ch35 - Practical Database Queries/listing35-1.php: -------------------------------------------------------------------------------- 1 | array("12309","45633","2010-12-19 01:13:42","$22.04","$5.67","$27.71"), 10 | '1' => array("12310","942","2010-12-19 01:15:12","$11.50","$3.40","$14.90"), 11 | '2' => array("12311","7879","2010-12-19 01:15:22","$95.99","$15.00","$110.99"), 12 | '3' => array("12312","55521","2010-12-19 01:30:45","$10.75","$3.00","$13.75") 13 | ); 14 | 15 | // Create an array of table attributes 16 | $attributes = array('border' => '1'); 17 | 18 | // Create the table object 19 | 20 | $table = new HTML_Table($attributes); 21 | 22 | // Set the headers 23 | 24 | $table->setHeaderContents(0, 0, "Order ID"); 25 | $table->setHeaderContents(0, 1, "Client ID"); 26 | $table->setHeaderContents(0, 2, "Order Time"); 27 | $table->setHeaderContents(0, 3, "Sub Total"); 28 | $table->setHeaderContents(0, 4, "Shipping Cost"); 29 | $table->setHeaderContents(0, 5, "Total Cost"); 30 | 31 | // Cycle through the array to produce the table data 32 | 33 | for($rownum = 0; $rownum < count($salesreport); $rownum++) { 34 | for($colnum = 0; $colnum < 6; $colnum++) { 35 | $table->setCellContents($rownum+1, $colnum, 36 | $salesreport[$rownum][$colnum]); 37 | } 38 | } 39 | 40 | // Output the data 41 | 42 | echo $table->toHTML(); 43 | 44 | ?> 45 | 46 | -------------------------------------------------------------------------------- /ch35 - Practical Database Queries/listing35-2.php: -------------------------------------------------------------------------------- 1 | '1'); 11 | 12 | // Create the table object 13 | $table = new HTML_Table($attributes); 14 | 15 | // Set the headers 16 | 17 | $table->setHeaderContents(0, 0, "Order ID"); 18 | $table->setHeaderContents(0, 1, "Client ID"); 19 | $table->setHeaderContents(0, 2, "Order Time"); 20 | $table->setHeaderContents(0, 3, "Sub Total"); 21 | $table->setHeaderContents(0, 4, "Shipping Cost"); 22 | $table->setHeaderContents(0, 5, "Total Cost"); 23 | 24 | // Cycle through the array to produce the table data 25 | 26 | // Create and execute the query 27 | $query = "SELECT id AS `Order ID`, client_id AS `Client ID`, 28 | order_time AS `Order Time`, 29 | CONCAT('$', sub_total) AS `Sub Total`, 30 | CONCAT('$', shipping_cost) AS `Shipping Cost`, 31 | CONCAT('$', total_cost) AS `Total Cost` 32 | FROM sales ORDER BY id"; 33 | 34 | $stmt = $mysqli->prepare($query); 35 | 36 | $stmt->execute(); 37 | 38 | $stmt->bind_result($orderID, $clientID, $time, $subtotal, $shipping, $total); 39 | 40 | // Begin at row 1 so don't overwrite the header 41 | $rownum = 1; 42 | 43 | // Format each row 44 | 45 | while ($stmt->fetch()) { 46 | 47 | $table->setCellContents($rownum, 0, $orderID); 48 | $table->setCellContents($rownum, 1, $clientID); 49 | $table->setCellContents($rownum, 2, $time); 50 | $table->setCellContents($rownum, 3, $subtotal); 51 | $table->setCellContents($rownum, 4, $shipping); 52 | $table->setCellContents($rownum, 5, $total); 53 | 54 | $rownum++; 55 | 56 | } 57 | 58 | // Output the data 59 | echo $table->toHTML(); 60 | 61 | // Close the MySQL connection 62 | $mysqli->close(); 63 | 64 | ?> 65 | 66 | -------------------------------------------------------------------------------- /ch35 - Practical Database Queries/member_to_vehicle.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE member_to_vehicle ( 2 | member_id INT UNSIGNED NOT NULL, 3 | vehicle_id INT UNSIGNED NOT NULL, 4 | PRIMARY KEY(member_id, vehicle_id)); 5 | 6 | -------------------------------------------------------------------------------- /ch35 - Practical Database Queries/products.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE products ( 2 | id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, 3 | product_id VARCHAR(8) NOT NULL, 4 | name VARCHAR(25) NOT NULL, 5 | price DECIMAL(5,2) NOT NULL, 6 | description MEDIUMTEXT NOT NULL 7 | ); 8 | 9 | -------------------------------------------------------------------------------- /ch35 - Practical Database Queries/sales.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE sales ( 2 | id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, 3 | client_id INT UNSIGNED NOT NULL, 4 | order_time TIMESTAMP NOT NULL, 5 | sub_total DECIMAL(8,2) NOT NULL, 6 | shipping_cost DECIMAL(8,2) NOT NULL, 7 | total_cost DECIMAL(8,2) NOT NULL 8 | ); 9 | 10 | -------------------------------------------------------------------------------- /ch35 - Practical Database Queries/subquery.php: -------------------------------------------------------------------------------- 1 | prepare("SELECT id, first_name, last_name FROM members 6 | WHERE zip = (SELECT zip FROM members WHERE id=?)"); 7 | 8 | $stmt->bind_param("ii", $recordstart, $pagesize); 9 | 10 | $stmt->execute(); 11 | 12 | // Loop over data per usual 13 | 14 | ?> 15 | 16 | -------------------------------------------------------------------------------- /ch35 - Practical Database Queries/vehicles.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE vehicles ( 2 | id INT UNSIGNED NOT NULL AUTO_INCREMENT, 3 | name VARCHAR(25) NOT NULL, 4 | description VARCHAR(100), 5 | PRIMARY KEY(id)); 6 | 7 | -------------------------------------------------------------------------------- /ch36 - Indexes and Searching/bookmarks.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE bookmarks ( 2 | id INT UNSIGNED NOT NULL AUTO_INCREMENT, 3 | name VARCHAR(75) NOT NULL, 4 | url VARCHAR(200) NOT NULL, 5 | description MEDIUMTEXT NOT NULL, 6 | PRIMARY KEY(id)); 7 | 8 | 9 | INSERT INTO bookmarks (name, url, description) 10 | VALUES("Apress", "www.apress.com", "Computer books"); 11 | INSERT INTO bookmarks (name, url, description) 12 | VALUES("Google", "www.google.com", "Search engine"); 13 | INSERT INTO bookmarks (name, url, description) 14 | VALUES("W. Jason Gilmore", "www.wjgilmore.com", "Jason's website"); 15 | 16 | -------------------------------------------------------------------------------- /ch36 - Indexes and Searching/bookmarks_fulltext.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE bookmarks ( 2 | id INT UNSIGNED NOT NULL AUTO_INCREMENT, 3 | name VARCHAR(75) NOT NULL, 4 | url VARCHAR(200) NOT NULL, 5 | description MEDIUMTEXT NOT NULL, 6 | FULLTEXT(description), 7 | PRIMARY KEY(id)); 8 | 9 | -------------------------------------------------------------------------------- /ch36 - Indexes and Searching/bookmarks_v2.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE bookmarks ( 2 | id INT UNSIGNED NOT NULL AUTO_INCREMENT, 3 | name VARCHAR(75) NOT NULL, 4 | url VARCHAR(200) NOT NULL UNIQUE, 5 | description MEDIUMTEXT NOT NULL, 6 | PRIMARY KEY(id)); 7 | 8 | -------------------------------------------------------------------------------- /ch36 - Indexes and Searching/bookmarks_v3.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE bookmarks ( 2 | id INT UNSIGNED NOT NULL AUTO_INCREMENT, 3 | name VARCHAR(75) NOT NULL UNIQUE, 4 | url VARCHAR(200) NOT NULL UNIQUE, 5 | description MEDIUMTEXT NOT NULL, 6 | PRIMARY KEY(id)); 7 | 8 | -------------------------------------------------------------------------------- /ch36 - Indexes and Searching/bookmarks_v4.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE bookmarks ( 2 | id INT UNSIGNED NOT NULL AUTO_INCREMENT, 3 | name VARCHAR(75) NOT NULL, 4 | url VARCHAR(200) NOT NULL, 5 | UNIQUE(name, url), 6 | description MEDIUMTEXT NOT NULL, 7 | PRIMARY KEY(id)); 8 | 9 | -------------------------------------------------------------------------------- /ch36 - Indexes and Searching/employees.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE employees ( 2 | id INT UNSIGNED NOT NULL AUTO_INCREMENT, 3 | firstname VARCHAR(100) NOT NULL, 4 | lastname VARCHAR(100) NOT NULL, 5 | email VARCHAR(100) NOT NULL UNIQUE, 6 | INDEX (lastname), 7 | PRIMARY KEY(id)); 8 | 9 | -------------------------------------------------------------------------------- /ch36 - Indexes and Searching/employees_v2.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE employees ( 2 | id INT UNSIGNED NOT NULL AUTO_INCREMENT, 3 | firstname VARCHAR(100) NOT NULL, 4 | lastname VARCHAR(100) NOT NULL, 5 | email VARCHAR(100) NOT NULL UNIQUE, 6 | INDEX (lastname(5)), 7 | PRIMARY KEY(id)); 8 | 9 | -------------------------------------------------------------------------------- /ch36 - Indexes and Searching/employees_v3.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE employees ( 2 | id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT, 3 | lastname VARCHAR(35) NOT NULL, 4 | firstname VARCHAR(35) NOT NULL, 5 | email VARCHAR(55) NOT NULL UNIQUE, 6 | INDEX name (lastname, firstname), 7 | PRIMARY KEY(id)); 8 | -------------------------------------------------------------------------------- /ch36 - Indexes and Searching/listing36_3.php: -------------------------------------------------------------------------------- 1 |

2 | Search the online resources database:
3 |
4 | Keywords:
5 |
6 | 7 | 8 |

9 | 10 | prepare("SELECT name, url FROM bookmarks 20 | WHERE MATCH(description) AGAINST(?)"); 21 | 22 | $stmt->bind_param('s', $_POST['keywords']); 23 | 24 | $stmt->execute(); 25 | 26 | $stmt->store_result(); 27 | 28 | // Output retrieved rows or display appropriate message 29 | if ($stmt->num_rows > 0) { 30 | 31 | $stmt->bind_result($url, $name); 32 | 33 | while ($result->fetch) 34 | printf("%s
", $url, $name); 35 | } else { 36 | printf("No results found."); 37 | } 38 | } 39 | ?> 40 | 41 | -------------------------------------------------------------------------------- /ch36 - Indexes and Searching/searchextended.php: -------------------------------------------------------------------------------- 1 |

2 | Search the employee database:
3 |
4 | Keyword:
5 |
6 | Field:
7 | 12 | 13 | 14 |

15 | 16 | prepare("SELECT firstname, lastname, email 26 | FROM employees WHERE lastname = ?"); 27 | } elseif ($_POST['field'] == "email") { 28 | $stmt = $db->prepare("SELECT firstname, lastname, email 29 | FROM employees WHERE email = ?"); 30 | } 31 | 32 | $stmt->bind_param('s', $_POST['keyword']); 33 | 34 | $stmt->execute(); 35 | 36 | $stmt->store_result(); 37 | 38 | // If records found, output them 39 | if ($stmt->num_rows > 0) { 40 | 41 | $stmt->bind_result($firstName, $lastName, $email); 42 | 43 | while ($stmt->fetch()) 44 | printf("%s, %s (%s)
", $lastName, $firstName, $email); 45 | 46 | } else { 47 | echo "No results found."; 48 | } 49 | } 50 | ?> 51 | 52 | -------------------------------------------------------------------------------- /ch36 - Indexes and Searching/simplesearch.php: -------------------------------------------------------------------------------- 1 |

2 | Search the employee database:
3 |
4 | Last name:
5 |
6 | 7 | 8 |

9 | 10 | prepare("SELECT firstname, lastname, email FROM employees 21 | WHERE lastname=?"); 22 | 23 | $stmt->bind_param('s', $_POST['lastname']); 24 | 25 | $stmt->execute(); 26 | 27 | $stmt->store_result(); 28 | 29 | // If records found, output them 30 | if ($stmt->num_rows > 0) { 31 | 32 | $stmt->bind_result($firstName, $lastName, $email); 33 | 34 | while ($stmt->fetch()) 35 | printf("%s, %s (%s)
", $lastName, $firstName, $email); 36 | } else { 37 | echo "No results found."; 38 | } 39 | 40 | } 41 | 42 | ?> 43 | 44 | -------------------------------------------------------------------------------- /ch37 - Transactions/customers.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE customers ( 2 | id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, 3 | name VARCHAR(255) NOT NULL 4 | ) ENGINE=InnoDB; 5 | 6 | -------------------------------------------------------------------------------- /ch37 - Transactions/listing37_1.php: -------------------------------------------------------------------------------- 1 | getParticipantKey(); 11 | 12 | // Retrieve the item seller and price using some fictitious item class 13 | $item = new Item(); 14 | $sellerID = $item->getItemOwner($itemID); 15 | $price = $item->getPrice($itemID); 16 | 17 | // Instantiate the mysqli class 18 | $db = new mysqli("localhost","website","secret","chapter37"); 19 | 20 | // Disable the autocommit feature 21 | $db->autocommit(FALSE); 22 | 23 | // Debit buyer's account 24 | 25 | $stmt = $db->prepare("UPDATE participants SET cash = cash - ? WHERE id = ?"); 26 | 27 | $stmt->bind_param('di', $price, $buyerID); 28 | 29 | $stmt->execute(); 30 | 31 | if ($db->affected_rows != 1) 32 | $success = FALSE; 33 | 34 | // Credit seller's account 35 | $query = $db->prepare("UPDATE participants SET cash = cash + ? WHERE id = ?"); 36 | 37 | $stmt->bind_param('di', $price, $sellerID); 38 | 39 | $stmt->execute(); 40 | 41 | if ($db->affected_rows != 1) 42 | $success = FALSE; 43 | 44 | // Update trunk item ownership. If it fails, set $success to FALSE 45 | $stmt = $db->prepare("UPDATE trunks SET owner = ? WHERE id = ?"); 46 | 47 | $stmt->bind_param('ii', $buyerID, $itemID); 48 | 49 | $stmt->execute(); 50 | 51 | if ($db->affected_rows != 1) 52 | $success = FALSE; 53 | 54 | // If $success is TRUE, commit transaction, otherwise roll back changes 55 | if ($success) { 56 | $db->commit(); 57 | echo "The swap took place! Congratulations!"; 58 | } else { 59 | $db->rollback(); 60 | echo "There was a problem with the swap!"; 61 | } 62 | 63 | ?> 64 | 65 | -------------------------------------------------------------------------------- /ch37 - Transactions/participants.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE participants ( 2 | id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, 3 | name VARCHAR(35) NOT NULL, 4 | email VARCHAR(45) NOT NULL, 5 | cash DECIMAL(5,2) NOT NULL 6 | ) ENGINE=InnoDB; 7 | 8 | -------------------------------------------------------------------------------- /ch37 - Transactions/trunks.php: -------------------------------------------------------------------------------- 1 | CREATE TABLE trunks ( 2 | id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, 3 | owner SMALLINT UNSIGNED NOT NULL REFERENCES participants(id), 4 | name VARCHAR(25) NOT NULL, 5 | price DECIMAL(5,2) NOT NULL, 6 | description MEDIUMTEXT NOT NULL 7 | ) ENGINE=InnoDB; 8 | 9 | -------------------------------------------------------------------------------- /ch38 - Importing and Exporting Data/load_table_data_with_php.php: -------------------------------------------------------------------------------- 1 | query($query); 24 | } 25 | 26 | fclose($fh); 27 | $mysqli->close(); 28 | ?> 29 | 30 | -------------------------------------------------------------------------------- /ch38 - Importing and Exporting Data/sales1.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE sales ( 2 | id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, 3 | client_id SMALLINT UNSIGNED NOT NULL, 4 | order_time TIMESTAMP NOT NULL, 5 | sub_total DECIMAL(8,2) NOT NULL, 6 | shipping_cost DECIMAL(8,2) NOT NULL, 7 | total_cost DECIMAL(8,2) NOT NULL 8 | ); 9 | 10 | -------------------------------------------------------------------------------- /contributing.md: -------------------------------------------------------------------------------- 1 | # Contributing to Apress Source Code 2 | 3 | Copyright for Apress source code belongs to the author(s). However, under fair use you are encouraged to fork and contribute minor corrections and updates for the benefit of the author(s) and other readers. 4 | 5 | ## How to Contribute 6 | 7 | 1. Make sure you have a GitHub account. 8 | 2. Fork the repository for the relevant book. 9 | 3. Create a new branch on which to make your change, e.g. 10 | `git checkout -b my_code_contribution` 11 | 4. Commit your change. Include a commit message describing the correction. Please note that if your commit message is not clear, the correction will not be accepted. 12 | 5. Submit a pull request. 13 | 14 | Thank you for your contribution! --------------------------------------------------------------------------------
%s
%s%s%s%s