Commit 09d942b4 authored by O'Reilly Media, Inc.'s avatar O'Reilly Media, Inc.
Browse files

Initial commit

parents
Loading
Loading
Loading
Loading
+399 −0
Changes for 9780596514013_ex_code_updated_7_15/appa.txt: 399 added lines, 0 removed lines.
Original line number Diff line number Diff line
appendix: Solutions to Chapter Questions
==================

switch ($action) {
  case "add":
    $x = $x+y;
    break;
  case "subtract":
    $x = $x-y;
    break;
  case "multiply":
    $x = $x*$y;
    break;
  case "divide":
    $x = $x/$y;
    break;
}

    
    
====================================

<?php
for ($num = 10; $num >= 1; $num&#8722;&#8722;) {
    print "$num<br>";
}
?>

    
    
====================================

<?php
function toast( $minutes ){

  //do the toasting here
  echo ("done.");
}
?>

    
    
====================================

<?php
toast(5);
?>

    
    
====================================

<?php
$months[]='January';
$months[]='February';
$months[]='March';
$months[]='April';
$months[]='May';
$months[]='June';
$months[]='July';
$months[]='August';
$months[]='September';
$months[]='October';
$months[]='November';
$months[]='December';
?>

    
    
====================================

array('January,'February','March','April','May','June','July','August',
'September','October','November','December');

    
    
====================================

<?php
$months= array('January' => 31,
               'February' => 28,
               'March' => 31,
               'April' => 30,
               'May' => 31,
               'June' => 30,
               'July' => 31,
               'August' => 31,
               'September' => 30,
               'October' => 31,
               'November' => 30,
               'December' => 31);
?>

    
    
====================================

<?php
$months= array('January' => 31,
               'February' => 28,
               'March' => 31,
               'April' => 30,
               'May' => 31,
               'June' => 30,
               'July' => 31,
               'August' => 31,
               'September' => 30,
               'October' => 31,
               'November' => 30,
               'December' => 31);
var_dump($months);
?>

    
    
====================================

CREATE TABLE months (
   month_id INT NOT NULL AUTO_INCREMENT,
   month VARCHAR (20),
   days INT,
   PRIMARY KEY (month_id));

    
    
====================================

INSERT INTO months VALUES (NULL,'January',31);
INSERT INTO months VALUES (NULL,'February',28);
INSERT INTO months VALUES (NULL,'March',31);
INSERT INTO months VALUES (NULL,'April',30);
INSERT INTO months VALUES (NULL,'May',31);
INSERT INTO months VALUES (NULL,'June',30);
INSERT INTO months VALUES (NULL,'July',31);
INSERT INTO months VALUES (NULL,'August',31);
INSERT INTO months VALUES (NULL,'September',30);
INSERT INTO months VALUES (NULL,'October',31);
INSERT INTO months VALUES (NULL,'November',30);
INSERT INTO months VALUES (NULL,'December',31);

    
    
====================================

mysqldump -u root -p blog > my_backup.sql

    
    
====================================

mysql -u root -p -D test < my_backup.sql

    
    
====================================

mysql://db_username:db_password@db_host/db_database:
mysql://joe:my$ql@oreilly.com/survey

    
    
====================================

<?php
//set the connection details
$db_host='oreilly.com';
$db_database='survey';
$db_username='joe';
$db_password='my$ql';
//call mysql_connect to connect
$connection = mysql_connect($db_host, $db_username, $db_password);
if (!$connection){
die ("Could not connect to the database: <br />". mysql_error(  ));
}
//select the database using mysql_select_db
$db_select = mysql_select_db($db_database);
if (!$db_select){
die ("Could not select the database: <br />". mysql_error(  ));
}
?>

    
    
====================================

<?php
$query = "SELECT * FROM authors";
$result = mysql_query( $query );
if (!$result){    die ("Could not query the database: <br />". mysql_error(  ));
}
while ($result_row = mysql_fetch_row(($result))){
    echo 'Author ID: '.$result_row[0] . '<br />';
    echo 'Title ID: '.$result_row[1] . '<br /> ';
    echo 'Author Name: '.$result_row[2] . '<br /><br />';
}
//Close the connection
mysql_close($connection);
?>

    
    
====================================

<?php
echo ('<form action="'.$_SERVER["PHP_SELF"].'" method="GET">');
echo ('
    <label>Username:<input type="text" name="username" size="10" maxlength="30" />
</label>
    <br />
    <label>Password:<input type="text" name="password" size="10" maxlength="30" />
</label>
    <input type="submit" value="Submit" />
    </form>
');
?>

    
    
====================================

<?php
//Get the username and password from the GET global array
$username = $_GET["username"];
$password = $_GET["password"];
//determine if this is after the form's been submitted
if (!empty($username)){
  //display the values from the submission
  echo ("Username: $username<br>");
  echo ("Password: $password<br>");
}
else {
//display the form
echo ('<form action="'.$_SERVER["PHP_SELF"].'" method="GET">');
echo ('
        <label>Username:<input type="text" name="username" size="10"
maxlength="30" /></label>
        <br />
        <label>Password:<input type="text" name="password" size="10"
maxlength="30" /></label>
        <input type="submit" value="Submit" />
        </form>
    ');
}
?>

    
    
====================================

SELECT * FROM authors WHERE author LIKE 'A%''

    
    
====================================

if (checkdate(1,31,2045)) {
    echo('Date is valid.');
}
else {
    echo ('Invalid date.');
}

    
    
====================================

<?php
$timestamp= mktime(1,31,2045);
echo date("l",$timestamp);
?>

    
    
====================================

<?php
$status=rename('upload.tmp','sample.jpg');
if ($status) {
    echo ("Renamed file.");
}
?>

    
    
====================================

<?php
require_once('db_login.php');
//sets the values for the database connection
require_once('DB.php');
//connect to the database
$connection = DB::connect("mysql://$db_username:$db_password@$db_host/$db_database");
if (DB::isError($connection)){
    die ("Could not connect to the database: <br />". DB::errorMessage($connection));
}
//modify the table
$query = "ALTER TABLE books ADD published_date date";
//check for an error
$result = $connection->query($query);
if (DB::isError($result)){
    die("Could not query the database: <br />". $query." ".DB::errorMessage($result));
}
echo "Modified successfully!";
$connection->disconnect(  );
?>

    
    
====================================

<?php
    session_start(  );
    $_SESSION['user_id'] = 1;
?>

    
    
====================================

<?php
    session_start(  );
    echo $_SESSION['user_id'];
?>

    
    
====================================

alert("The username field must be at least six characters");

    
    
====================================

'/^/d{5}(-/d{4})?$/'

    
    
====================================

<?php
$pattern = '/^/d{5}(-/d{4})?$/';
$matched=preg_match($pattern, $zipcode, $matches);
if ($matched) {
  echo ("Zipcode OK.");
}
?>

    
    
====================================

<?php
  // put full path to Smarty.class.php
  require('/usr/share/php/Smarty/Smarty.class.php');
  $smarty = new Smarty(  );
  $smarty->template_dir = '/home/www/htmlkb/smarty/templates';
  $smarty->compile_dir = '/home/www/htmlkb/smarty/templates_c';
  $smarty->cache_dir = '/home/www/htmlkb/smarty/cache';
  $smarty->config_dir = '/home/www/htmlkb/smarty/configs';
  $blog_title="PHP and MySQL Zone";
?>

    
    
====================================

insert into categories values (NULL, 'Bugs');

    
    
====================================

<?php
/*
 * this file welcomes the user.
 * this file welcomes the user and uses proper code styles.
 *
 * Copyright 2006 (c) O'Reilly Media, Inc.
 *
 * @version   $Id: coding_standards_example.html,v 1.2 2006/1/19 24:49:50
 *
 */
//verify the user
if ($_GET[user_id] == 'Admin')
{
  //Welcome the admin user to the control panel.
  echo ('Welcome to the control panel.');
}
else
{
  //Welcome other user.
  echo ('Welcome.');
}
?>

    
    
==================
 No newline at end of file
+116 −0
Changes for 9780596514013_ex_code_updated_7_15/ch01.txt: 116 added lines, 0 removed lines.
Original line number Diff line number Diff line
chapter: Dynamic Content and the Web
==================
Example: A PHP function to insert a comment into a comments database table
<?php
//A function to insert a comment into a comments table based on
//the $comment parameter.
//The database name is also a parameter

function add_comment($comment,$database){
    // Add a comment
    // As a security measure, escape any special characters in comment.
    $comment=mysql_real_escape_string($comment);

    // This is the SQL command
    $sql_insert = "INSERT INTO 'comments' (body) VALUES ('$comment')";

    // Select the database
    mysql_select_db($database);

    $success = mysql_query($sql_insert) or die(mysql_error(  ));

    // print the page header
    print('
        <html>
            <head>
                <title>Remove User</title>
                <link rel="stylesheet" type="text/css" href="example.css" />
            </head>
            <body>
                <div class="comments">');

    // Check to see if the insert was successful
    if ($success){
        // Tell the user it was successful
        print("The comment $comment was inserted successfully.");
    }
    else {
        // Tell the user it was not successful
        print("The comment $comment could not be inserted. Please try again later.");
    }

    // Print the page footer
    print('</div></body></html>');
}

?>

    
    
====================================
Example: A PHP Smarty template
<html>
    <head>
        <title>My Books</title>
    </head>
    <body>
        <p>Favorite Books:</p>
        <p>
            Title: {$title}<br />
            Author: {$author}
        </p>
    </body>
</html>

    
    
====================================
Example: The resulting HTML code after template substitution and processing
<html>
    <head>
        <title>My Books</title>
    </head>
    <body>
        <p>Favorite Books:</p>
        <p>
            Title: Java in a Nutshell<br />
            Author: Flanagan
        </p>
    </body>
</html>

    
    
====================================

<html>
    <head>
        <title>CSS Example</title>
        <style type="text/css">
            h4, b {color: #80D92F; font-family: arial; }
            p { text-indent: 2cm; background: yellow; font-family: courier;}
        </style>
    </head>

    <body>
        <h3>Learn how to use CSS on your web sites!</h3>
        <h4>It's cool, it's amazing, it even saves you time!</h4>
        <p>Isn't this <b>nifty</b>?</p>
    </body>
</html>

    
    
====================================

<tag>Isn't this nifty?</tag>

    
    
====================================

<h3>Learn how to use CSS on your web sites!</h3>

    
    
==================
 No newline at end of file
+78 −0
Changes for 9780596514013_ex_code_updated_7_15/ch02.txt: 78 added lines, 0 removed lines.
Original line number Diff line number Diff line
chapter: Installation
==================

<?php phpinfo(  ); ?>

    
    
====================================

sudo vi /etc/httpd/httpd.conf

    
    
====================================

%s/#LoadModule php/LoadModule php/

    
    
====================================

%s/#AddModule php/addModule php/

    
    
====================================

:%s/index.html/index.html index.php/

    
    
====================================

Include /private/etc/httpd/users

    
    
====================================

<IfModule mod_php4.c>
AddType application/x-httpd-php .php
AddType application/x-httpd-php .php4
AddType application/x-httpd-php-source .phps
</IfModule>

    
    
====================================

<escape>:wq

    
    
====================================

vi ~/Sites/test.php
o
<?php phpinfo(  ) ?>
<escape>:wq

    
    
====================================

extension_dir = C:\php\extensions
extension=php_mysql.dll

    
    
====================================

sudo apt-get install mysql
sudo apt-get install mysql-client
daemonic enable mysql

    
    
==================
 No newline at end of file
+490 −0
Changes for 9780596514013_ex_code_updated_7_15/ch03.txt: 490 added lines, 0 removed lines.
Original line number Diff line number Diff line
chapter: Exploring PHP
==================
Example: All you need to start with PHP is a simple HTML document
<html>
    <head>
        <title>Hello World</title>
    </head>
    <body>
        <p>I sure wish I had something to say.</p>
    </body>
</html>

    
    
====================================
Example: A wrong way to add some PHP code to the HTML file
<html>
    <head>
        <title>Hello World</title>
    </head>
    <body>
        echo "<p>Now I have something to say.</p>";
    </body>
</html>

    
    
====================================
Example: Correctly calling print in hello.php
<html>
    <head>
        <title>Hello World</title>
    </head>
    <body>
        <?php
        print "Hello world!<br />";
        print "Goodbye.<br />";
        print "Over and out.";
        ?>
    </body>
</html>

    
    
====================================
Example: The HTML markup produced by the PHP code in 
<html>
<head>
        <title>Hello World</title>
    </head>
    <body>
        Hello world!<br />Goodbye.<br />Over and out.
    </body>
</html>

    
    
====================================
Example: Using comments to make your code easier to read
<html>
    <head>
        <title>Hello World</title>
    </head>
    <body>
        <?php

        // A single line comment could say that we are going to
        // print hello world.

        /* This is how to do a
           multiline comment and could be used to comment out a block
           of code */

        echo "Hello world!<br />";
        echo "Goodbye.<br />";

        ?>
    </body>
</html>

    
    
====================================

$variable_name = value;

    
    
====================================

<?php
$age = 30;
?>

    
    
====================================
Example: Reassigning a variable
<?php
$age = 30;
$age = 31;
echo $age;
?>

    
    
====================================

31

    
    
====================================
Example: The default handling of variable scope
<?php

// Define a function
function birthday(  ){
    // Set age to 1
    $age = 1;
}

// Set age to 30
$age = 30;

// Call the function
birthday(  );

// Display the age
echo $age;

?>

    
    
====================================

30

    
    
====================================
Example: Using a global variable changes the result
<?php

// Define a function
function birthday(  ){
    // Define age as a global variable
    global $age;

    // Add one to the age value
    $age = $age + 1;
}

// Set age to 30
$age = 30;

// Call the function
birthday(  );

// Display the age
echo $age;

?>

    
    
====================================

31

    
    
====================================
Example: A static variable remembering its last value
<?php

// Define the function

function birthday(  ){
    // Define age as a static variable
    static $age = 0;

    // Add one to the age value
    $age = $age + 1;

    // Print the static age variable
    echo "Birthday number $age<br />";
}

// Set age to 30
$age = 30;

// Call the function twice
birthday(  );
birthday(  );

// Display the age
echo "Age: $age<br />";

?>

    
    
====================================

Birthday number 1
Birthday number 2
Age: 30

    
    
====================================
Example: PHP_SELF being used with a file called test.php
<?php
echo htmlentities($_SERVER["PHP_SELF"]);
?>

    
    
====================================

/test.php

    
    
====================================
Example: Working with strings
<?php
$my_string = "Margaritaville - Suntan Oil Application!";
echo "Margaritaville - Suntan Oil Application!";
?>

    
    
====================================
Example: Using a variable in a string definition
<?php
$my_string = "Margaritaville - Suntan Oil Application!";
echo "Time for $my_string";
?>

    
    
====================================
Example: Single quotes used in a string assignment
<?php
$my_string = 'Margaritaville - Suntan Oil Application!';
echo $my_string;
?>

    
    
====================================
Example: Various special characters in string assignments
<?php
$newline = "A newline is \n";
$return = "A carriage return is \r";
$tab = "A tab is \t";
$dollar = "A dollar sign is \$";
$doublequote = "A double-quote is \"";
?>

    
    
====================================
Example: Breaking echo with special characters
// This won't work because of the quotes around specialH2!
echo "<h2 class="specialH2">Margaritaville!</h2>";
?>
specialH2

    
    
====================================

Parse error: parse error, unexpected T_STRING, expecting ','
or ';' in /home/www/html/oreilly/ch3/parse.php on line 3

    
    
====================================
Example: Correct escaping of special characters
<?php
// OK because we used single quotes
echo "<h2 class=\"specialH2\">Margaritaville!</h2>";
echo '<h2 class="specialH2">Margaritaville!</h2>';
?>

    
    
====================================
Example: Using strcasecmp to compare two strings
<?php

$name1 = "Bill";
$name2 = "BILL";

$result = strcasecmp($name1, $name2);

if (!$result){
    echo "They match.";
}

?>

    
    
====================================

They match.

    
    
====================================
Example: Concatenating strings together
<?php
$my_string = "Hello Max. My name is: ";
$newline = "<br />";
echo $my_string . "Paula" . $newline;
echo "Hi, I'm Max. Who are you? " . $my_string . $newline;
echo "Hi, I'm Max. Who are you? " . $my_string . "Paula";
//The last line is the same as echo "Hi, I'm Max. Who are you? $my_string Paula";
?>

    
    
====================================
Example: Combining a string and a number
<?php
$str = "This is an example of ". 3 ." in the middle of a string.";
echo $str;
?>

    
    
====================================

This is an example of 3 in the middle of a string.

    
    
====================================
Example: Using a constant in your program
<?php
define("HELLO", "Hello world! ");
echo HELLO; // outputs "Hello world!"

$constant_name = "HELLO";
echo constant($constant_name);
?>

    
    
====================================

Hello world! Hello world!

    
    
====================================

// define ("HELLO", "Hello world!");

    
    
====================================

HELLO

    
    
====================================
Example: Echoing the line and file predefined constants for a script called predefined_constants.php
<?php
echo "Executing line " . __LINE__ . " of PHP script " . __FILE_  _ . ".";
?>

    
    
====================================

Executing line 2 of PHP script /home/www/html/oreilly/ch3/predefined_constants.php.

    
    
====================================
Example: PHP mathematical function usage
<?php>
$sunny_days=300;
$Margaritaville_sunny_days_ratio=$sunny_days/365;
echo $Margaritaville_sunny_days_ratio;
?>

    
    
====================================

$counter=$counter+1;

    
    
====================================

$counter+=1;

    
    
====================================

$counter++;

    
    
====================================

$counter+=1;

    
    
====================================
Example: Using autoincrement to add to a variable
<?php
$counter=1;
$counter++;
echo $counter
?>

    
    
====================================

2

    
    
====================================
Example: Using the autodecrement operator
<?php
$counter=1;
$counter--;
echo $counter
?>

    
    
====================================

0

    
    
====================================

--$counter;

    
    
====================================

++$counter;

    
    
====================================
Example: Using pre- and postincrement
<?php
$test=1;
echo "Preincrement: ".(++$test);
echo "<BR>";
echo "Value afterwards: ".$test;
echo "<BR>";
$test=1;
echo "Postincrement: ".($test++);
echo "<BR>";
echo "Value afterwards: ".$test;
?>

    
    
====================================

Preincrement: 2
Value afterwards: 2
Postincrement: 1
Value afterwards: 2

    
    
==================
 No newline at end of file
+424 −0

File added.

Preview size limit exceeded, changes collapsed.

Loading