Yale University School of Art
1156 Chapel Street, POB 208339
New Haven, Connecticut, 06520-8339
(203) 432-2600
ART 742 NETWORKS & TRANSACTIONS 1: 2009

SIGNUP APRIL 27

  Dan    Tam
12:15-1:00 Lauren A    Lauren H
1:00-1:45 Geoff    Lauren A
1:45-2:30 Ely Kim    Caspar Lam
2:30-3:15 Lauren F    Ely Kim
3:15-4:00 Caspar Lam    Geoff
4:00-4:45 Vance    Lauren F
4:45-5:30 Kate O    Vance
5:30-6:15 Steven    Kate O
6:15-7:00 Lauren H    Steven
8 or 9:00 → Sullivan’s
Last edited by: Geoffrey Edward Halber
Edit access: Sysop


GRAPHIC DESIGN, 742B, NETWORKS & TRANSACTIONS 1

Green Hall, Room 209
Mondays 1:30-5:30

How can graphic design influence and be influenced by the unpredictable encounters between one group and another? Or between quantities of unknown users on one side, and vast webs of fluctuating information on the other? In this first course of the Networks and Transactions sequence, we develop a typography appropriate for these pervasive conditions of the modern world. In addition to typographic concerns, fundamentals of programming‚and the PHP language in specific‚are learned through hands-on work. No previous programming experience necessary. Open to preliminary and first-year graphic design students, or by permission of the instructor. Dan Michaelson

Last edited by: Neil Donnelly
Edit access: Sysop

SEE ALSO:   SYLLABUS (PDF)    CLASS WEBSITE ’08    CLASS WEBSITE ’07   


ASSIGNMENT 3: DATABASE

Choose one of the following:

A) CMS

Create a simple content management system. Consider who may edit it (only you, a select group, a large group, or anyone), and who will be viewing it (only you, a select group, or a large group). What is the relationship between the following aspects:

  • content
  • content structure
  • user base
  • the template you create for input
  • and the template you create for output and links among content?

Finally, like a weather system, how does your system evolve over time?

or B) Art School website database

Analyze or re-use data found in the School of Art website database. I will give you read-only access to the entire database (about 600 pages, 5,000 magic modules, 11,000 page versions and 30,000 magic module versions, 450 users, 9 million page view records).

Last edited by: Dan Michaelson
Edit access: Sysop


SCHEDULE

  • March 2: Group crit
  • March 23: Individual meetings
  • March 30: Group crit: Assignment 2 (weather) due
  • April 6: Individual meetings
  • April 13: Group crit
  • April 20: Individual meetings
  • April 27: Individual meetings with Dan and Tamara: Assignment 3 (database) due
  • Thurs Apr 30: Prelim final reviews
  • Mon-Tues May 4-5: 1st-year final reviews
Last edited by: Dan Michaelson
Edit access: Sysop

OFFICE HOURS

Thursdays 6pm‚??8pm
Neil Donnelly
neil.donnelly@yale.edu

Sundays 5pm‚??7pm
Tara Kelton
tara.kelton@yale.edu

Last edited by: Neil Donnelly
Edit access: Sysop


RESOURCES

TextWrangler
The text editor you’ll use in this class

Sequel Pro
MySQL database client for Macintosh
Problems? Try the old version, called CocoaMySQL

PHP.net
PHP reference site, including a manual and function documentation

W3Schools
Good HTML reference site. Browse around the same site for CSS too.

Feed Proxy
Extension to view an RSS feed as raw XML in FIrefox

Prototype and Scriptaculous
JavaScript helper libraries (Scriptaculous is for animation and requires Prototype)
You can also download them both together directly from here

Firebug
Amazing extension to debug JavaScript in Firefox

Last edited by: Dan Michaelson
Edit access: Sysop

Some content management systems

The weather

Last edited by: Dan Michaelson
Edit access: Sysop


ASSIGNMENT 1: LETTERS AND NUMBERS

Last edited by: Lauren A Francescone
Edit access: Sysop


ASSIGNMENT 2: THE WEATHER

Choose one of the following:

A) Weather

Design a display of current weather conditions and/or the weather forecast— either for a single city (such as New Haven) or for multiple cities (which, if you wish, could be selected by the user). What kind of design system will you create to accommodate all possible weather conditions? Consider how your own agency as a designer can enter into such a project: as a system, what is the weather in your opinion? Yahoo provides a web service which will provide weather data to your program; I will show you how to use it.

B) Search

Following a similar approach as that discussed in (A), design an input and display for internet search results. Yahoo provides a web service which will provide search results on demand to your program, as raw data; your job is to form an opinion about internet search and develop a corresponding typography.

C) Yale map building views

I will provide you with a realtime feed of what buildings people are looking at on the online Yale campus map (http://yale.edu/map), and I ľll show you how to incorporate it into your program. Represent this information…

  • Sample request & response:
    http://business.yale.edu/map/recentBuildings.jsp
  • You’ll receive the most recent 25 views
  • Also available if you need it (ask Dan):
    • Building photographs
    • Map tile images
    • Building info (address etc.)
    • Building tenants (departments, department websites)
    • User IP address info (can be correlated to geography or on-campus/off-campus)

or D) Art School website page views or edits

I will provide you with a realtime feed of what pages people are viewing and editing on the Art School website (http://art.yale.edu), and I ľll show you how to incoroporate it into your program. Represent this information.

  • Sample request and response
  • You can request up to the most recent 1000 views or edits by changing the number above
  • Also available if you need (ask Dan):
    • User info for page views (name etc. for logged-in users; IP address and geographical information for all users)
    • More info about page contents, up to the complete content
    • Page edit history
Last edited by: Lauren Anne Adolfsen
Edit access: Sysop


LABS

  1. PHP basics
  2. HTML markup
  3. Arrays
  4. Reading files and XML
  5. Accessing a database

Possible extra topics:

Last edited by: Dan Michaelson
Edit access: Sysop


LAB 1

TOPICS COVERED

PHP

  • Code execution always goes in order, one step at a time, from top to bottom— except when a control structure such as a loop, a conditional, or a function changes that sequence. To understand code or write code, read and think in this step-by-step way.
  • Semicolon
  • Comments
  • Variable assignment
  • Text output
  • Conditionals and variable comparison
  • For loops
  • Functions
  • Receiving input from the URL query

HTML

  • Tags and attributes
  • Links
  • Images
  • Absolute and relative URLs
  • A bit of CSS for the purpose of absolute pixel positioning (typically on a <div> or an <img>)
  • Remember that you can use PHP to output any HTML tags (for example, conditionally), just like you output any other text; or to insert variables into HTML tags in any way. The browser then renders the resulting HTML.
Last edited by: Dan Michaelson
Edit access: Sysop


PHP basics
<?php

/* ------------- COMMENTS ------------- */

// One-line comment

/* Multi-line
    comment */
    
// Comment copiously!


/* ------------- OUTPUT ------------- */

// In PHP, all statements end with a semicolon (;)

echo(1); // Numeric value (outputs '6')

echo("5 + 1"); // String (double-quoted) (outputs "5 + 1")

echo('5 + 1'); // String (single-quoted) (also outputs "5 + 1")


/* ------------- VARIABLE ASSIGNMENT ------------- */

// In PHP, all variable names begin with a dollar-sign ($).
// After the $ they should start with a letter, and contain no spaces or punctuation except "_".
// Variable names are case-sensitive.
// Name your variables meaningfully! More meaningfully than $x and $y.

$x 3// This sets $x to 3

// Variable substitution in a double-quoted string
echo("The value of X is $x<br />");
// Outputs "The value if X is 3"

// No variable substitution in single-quoted strings
echo('The value of X is $x<br />');
// Outputs "The value of X is $x"

$y 3// This sets $y to 3

$y += 1// This adds 1 to $y, so now $y is 4

echo($y 1); // Output a variable
// Outputs "5"

$x $y 1;
// Now $x is 5

echo("Now the value of X is $x<br />"); // X has a different value now than it did before
// Outputs "Now the value of X is 5"



/* ------------- VARIABLE COMPARISON (a.k.a. conditionals) ------------- */

// Code between braces { } is executed only if $x is 5
// Notice double-equal for comparison, i.e. asking a question; single-equal for assignment.
// Also notice the condition has to go in parenthesis ( )
if ($x == 5) {
    echo(
"High five.");
    echo(
"!!");
}
// Otherwise code between the below { } is executed (i.e. only if $x is not 5)
else {
    echo(
"Not five.");
    
// You can nest conditions, as in "otherwise: if..."
    
if ($x 5) {
        echo(
"Down low");
    }
    else {
        echo(
"Too high");
    }
}

echo(
"This will happen either way.<br /><br />");



/* ------------- LOOPS ------------- */

// $i is set to 1.
// After the loop is executed each time, $i is increased by 1.
// The loop repeats if $i <= 5.
for ($i 1$i <= 5$i += 1) {
    echo(
$i);
    
// You can nest loops, as in "each time you do this, do that 5 times."
    // $j is set to 1.
    // After the loop is executed each time, $j is increased by 1.
    // The loop repeats if $j <= $i
    
for ($j 1$j <= $i$j += 1) {
        echo(
".");
    }
}
// Outputs "1.2..3...4....5....."

echo("<br />");


/* ------------- FUNCTIONS ------------- */

echo(negate($x));
// Outputs "-5"

// You can define functions anywhere in your code-- at the top or the bottom.
// This is a function that expects one parameter
// It returns the negative of the parameter
function negate($whatToNegate) {
    
$negatedValue $whatToNegate;
    return 
$negatedValue;
}

$z multiply($x$y);
// Doesn't output anything, just sets $z to 20

// This is a function that expects two parameters
// It returns the multiplied product of the parameters
function multiply($one$two) {
    return 
$one $two;
}

doSomething();
doSomething();
// Outputs "Something
//          Something"

// This is a function that expects no parameters
// It doesn't return anything
function doSomething() {
    echo(
"Something<br />");
}


/* ------------- RECEIVING VARIABLES FROM THE WEB REQUEST ------------- */

// To set $x and $y, enter the URL http://ernie.art.yale.edu/~yourname/yourscript.php?someValue=5&anotherValue=8

$x $_REQUEST["someValue"];
$y $_REQUEST["anotherValue"];

echo(
"Last, X is $x, Y is $y<br />");
// Outputs "Last, X is 5, Y is 8"

?>
Last edited by: Dan Michaelson
Edit access: Designer, Sysop

HTML (with some PHP mixed in)
<html>

    <head>
        <title>
            Greetings
        </title>
    </head>
    
    <body bgcolor="#FFFF00">
        <font face="Helvetica, Arial, sans-serif" color="#FF0000" size="7">
        
            Hello<br />world!
    
            <!-- Multi-line
            comment -->
            
            <p>
                <?php
                
                
// Get $x from the "?x=" parameter in the web request
                
$x $_REQUEST["x"];
                
                
// Output it bold if it's more than 5
                
if ($x 5) {
                    echo(
"<b>$x</b>");
                }
                
// Otherwise output it normal
                
else {
                    echo(
$x);
                }
                
                
?>
            </p>
            
            <!-- CSS style to create absolute positioning -->
            <div style="position: absolute; top: 40px; left: 300px; z-index: 2">
                Paragraph
                one
            </div>
            
            <p>
                <b>Paragraph</b> <i>two</i>
            </p>
            
            <!-- Use PHP to output an image tag only if $x is more than 5 -->
            <?php
            
            
if ($x 5) {
                echo(
'<p>');
                echo(
'<img src="images/sauron.jpg" width="200" height="100" />');
                echo(
'</p>');
            }
            
            
?>
    
            <!-- Another way to use PHP to output an image tag only if $x is more than 5 -->
            <?php
            
            
if ($x 5) {
            
            
?>
            
                <p>
                    <img src="images/sauron.jpg" width="200" height="100" />
                </p>
                
            <?php
            
            
}
            
            
?>
            
            <!-- Build a different image filename depending based on the value of $x -->
            <p>
                <img src="images/image<?php echo($x?>.jpg" width="200" height="100" />
            </p>
    
            <!-- Another syntax for the same thing $x -->
            <p>
                <img src="images/image<?= $x ?>.jpg" width="200" height="100" />
            </p>
    
            <!-- Link surrounding an image with an absolute URL -->
            <p>
                <a href="http://google.com"><img src="http://www.google.com/intl/en_ALL/images/logo.gif" /></a>
            </p>
            
            <!-- Link surrounding text -->
            <p>
                <a href="http://google.com">Go to Google</a>
            </p>
            
            <!-- Image with a relative URL -->
            <!-- CSS style positions it absolutely, and the top and left are based on $x and $y -->
            <img src="images/sauron.jpg" style="position: absolute; top: <?= $y ?>px; left: <?= $x ?>px; width: 400px; height: 400px; z-index: 1;" />
            
            <!-- Level-1 header -->
            <h1>
                Header
            </h1>
            
            <!-- Level-2 header, with custom styling -->
            <h2 style="font-family: Times, Times New Roman; color: blue; font-weight: bold; font-style: italic; text-decoration: underline; font-size: 24px; line-height: 28px;">
                Orbi scelerisque purus <span style="color: green;">interdum</span> pede. Aenean tempus aliquam eros. Nullam non tortor eu metus molestie suscipit.
            </h2>
                
        </font>
    </body>

</html>
Last edited by: Dan Michaelson
Edit access: Designer, Sysop

LAB 2

TOPICS COVERED

HTML and CSS

  • Forms
  • CSS selectors (choose an HTML tag, class, or id to style)
  • Stylesheet in the HTML document
  • Externally linked stylesheet

PHP

Last edited by: Dan Michaelson
Edit access: Sysop


input.php
<html>

    <head>
    
        <title>Tell me some information</title>
        
    </head>
    
    <body>
    
        <form action="output.php">
        
            Letter <input type="text" name="letter" />
            Number <input type="text" name="number" />
            
            <p>
                <input type="radio" name="color" value="red" />Red<br />
                <input type="radio" name="color" value="green" />Green<br />
                <input type="radio" name="color" value="blue" />Blue
            </p>
            
            <p>
                <input type="checkbox" name="yesno" value="yes" />Yes
            </p>
            
            <p>
                <select name="day">
                    <option value="sunday">Sunday</option>
                    <option value="monday">Monday</option>
                    <option value="tuesday">Tuesday</option>
                </select>
            </p>
                
            <input type="submit" value="Okay" />
                    
        </form>
    
    </body>

</html>
Last edited by: Dan Michaelson
Edit access: Designer, Sysop

output.php
<html>

    <head>
    
        <title>Output</title>

        <?php
            $letter 
$_REQUEST["letter"];
            
$number $_REQUEST["number"];
            
$color $_REQUEST["color"];
            
$yesno $_REQUEST["yesno"];
            
$day $_REQUEST["day"];
        
?>
        
    </head>
    
    <body>
    
        <p>
            <?php
                
echo("$letter<br />");
                echo(
"$number<br />");
                echo(
"$color<br />");
                echo(
"$yesno<br />");
                echo(
"$day<br />");
            
            
?>
        </p>        
        
        <p>
            <?= $letter ?><br />
            <?= $number ?><br />
            <?= $color ?><br />
            <?= $yesno ?><br />
            <?= $day ?><br />
        </p>
        
        <?php
        
            
if ($color == "red") {
                echo(
"<p style='color: #ff0000; font-size: 48px;'>$day</p>");
            }
            
        
?>
        
        <p>
            <?php
            
                
for ($i 1$i <= intval($number); $i += 1) {
                    echo(
$letter);
                    echo(
" ");
                }
            
            
?>
        </p>
        
        <p>
            <?php
            
                
for ($row 1$row <= 10$row += 1) {
                    for (
$column 1$column <= 10$column +=1) {
                        echo(
". ");
                    }
                    for (
$column 1$column <= 10$column +=1) {
                        echo(
"- ");
                    }
                    echo(
"<br />");
                }
            
            
?>
        </p>
        
    </body>

</html>
Last edited by: Dan Michaelson
Edit access: Designer, Sysop

stylesheet-embedded.php
<html>

    <head>
    
        <title>Styles</title>
        
        <style>
            
            body {
                color: blue;
            }
            
            p {
                font-family: Arial;
                font-size: 14px;
                line-height: 16px;
            }
            
            b {
                color: red;
                font-weight: normal;
            }
            
            i {
                color: green;
            }
            
            span {
                color: purple;
            }
            
            .important {
                font-size: 36px;
                line-height: 42px;
                text-decoration: underline;
            }
            
            p.important {
                background-color: yellow;
            }
            
            #header {
                position: absolute;
                top: 20px;
                left: 300px;
                background-color: teal;
            }
            
        </style>
        
    </head>
    
    <body>
    
        <p>
            Paragraph 1
        </p>
        
        <p class="important">
            Paragraph 2
        </p>
        
        <p>
            The quick <b class="important">brown</b> fox <i>jumps</i> over the lazy dog
        </p>
        
        <div id="header">
            This <span>text</span> is not in a paragraph.
        </div>
    
    </body>


</html>

Last edited by: Dan Michaelson
Edit access: Designer, Sysop

stylesheet-external.php
<html>

    <head>
    
        <title>Styles</title>
        
        <link rel="stylesheet" type="text/css" href="stylesheet.css" />
        
    </head>
    
    <body>
    
        <p>
            Paragraph 1
        </p>
        
        <p class="important">
            Paragraph 2
        </p>
        
        <p>
            The quick <b class="important">brown</b> fox <i>jumps</i> over the lazy dog
        </p>
        
        <div id="header">
            This <span>text</span> is not in a paragraph.
        </div>
    
    </body>

</html>
Last edited by: Dan Michaelson
Edit access: Designer, Sysop

stylesheet.css
body {
    color: blue;
}

p {
    font-family: Arial;
    font-size: 14px;
    line-height: 16px;
}

b {
    color: red;
    font-weight: normal;
}

i {
    color: green;
}

span {
    color: purple;
}

.important {
    font-size: 36px;
    line-height: 42px;
    text-decoration: underline;
}

p.important {
    background-color: yellow;
}

#header {
    position: absolute;
    top: 20px;
    left: 300px;
    background-color: teal;
}
Last edited by: Dan Michaelson
Edit access: Designer, Sysop

arrays.php
<html>

    <head>
    
        <title>People</title>
    
    </head>

    <body>
    
        <?php
        
            $number 
$_REQUEST["number"];
            
            
$names = array("Lauren""Geoff""Caspar""Steven""Lauren""Lauren""Tara""Neil""Vance""Ely""Kate");
            
$names[1] = "Geoffrey";

            echo(
$names[$number]);
            
            
$people = array(array("Lauren""F"), array("Geoff""M"), array("Caspar""M"));
            
            echo(
" ");
            echo(
$people[$number][1]);
            
            echo(
"<p>");
            
            
sort($names);
            
            for (
$i 0$i count($names); $i += 1) {
                
$newName str_replace("e""<b>E</b>"$names[$i]);
                echo(
$newName);
                echo(
" ");
            }
            
            echo(
"</p>");
            
            
$sentence "The quick brown fox jumps over the lazy dog.";
            
$words explode(" "$sentence);
            
            echo(
"<p>");
            echo(
"There were ");
            echo(
count($words));
            echo(
" words. ");
            echo(
"</p>");
            
            echo(
"<p>");
            for (
$i 0$i count($words); $i += 1) {
                echo(
$words[$i]);
                echo(
"---");
            }
            echo(
"</p>");

        
?>
    
    </body>

</html>
Last edited by: Dan Michaelson
Edit access: Designer, Sysop

LAB 3

TOPICS COVERED

  • Review of arrays
  • Arrays with indexes that are strings instead of numbers (also sometimes called an “associative array” or a “hash”)
  • foreach loop to loop through an array that has non-numerical indexes
  • Reading a file (stored on Ernie or on the internet) into a single string using file_get_contents
  • Reading a file (stored on Ernie or on the internet) into an array of lines using file
  • Brief discussion of object-oriented programming, just because SimpleXML uses an object-oriented syntax that we haven’t seen before; Flash’s ActionScript in next semester’s class is also object-oriented.
  • Parsing XML in PHP using SimpleXML

Also:

Resource:

  • For viewing raw XML feeds, Firefox displays XML more usefully than Safari does. But even in Firefox, RSS XML feeds such as Yahoo Weather still don’t display as the raw XML you need. To get around that, use the Feed Proxy service for Firefox.
Last edited by: Dan Michaelson
Edit access: Sysop


arrays2.php
<?php

// Get a number from a request parameter called "index", and store it in $index
$index $_REQUEST["index"];

// A normal (non-complex) variable (i.e. not an array) is technically called a "scalar" variable
$scalar "Apple";

// Make an array of four elements (numbered 0 through 3) and store it in $array
$array = array("Apple""Orange""Pear""Banana");

// Replace element 1 ("Orange") with "Grapes"
$array[1] = "Grapes";

// Output whichever element of the fruit array the user asked for by number
echo($array[$index]);

// Randomly sort the array's order
shuffle($array);

// Loop through the array and output each element
for ($i 0$i count($array); $i += 1) {

    echo(
"Element $i is $array[$i]");

}

// Get a sentence from a request parameter called "sentence", and store it in $sentence
$sentence $_REQUEST["sentence"];

// Make an array of words by dividing the sentence up according to the space character; and store the array in $words
$words explode(" "$sentence);

// Randomly sort the array's order
shuffle($words);

// Loop through the array of words and output each word
for ($i 0$i count($words); $i += 1) {

    
$word $words[$i];
    
// Capitalize each word before outputting it
    
echo(ucfirst($word));
    
// Output a space after each word
    
echo(" ");

}

// You can make an array with non-consecutive indexes
$array = array(=> "Apple"=> "Orange"=> "Pear"=> "Banana");

echo(
$array[$index]);

// You can also make an array with indexes that are strings rather than numbers
$qualities = array("color" => "red""sound" => "loud""temperature" => "warm");

// Add an element to the array, with index "taste" and value "sour"
$qualities["taste"] = "sour";

// Replace the "color" element ("red") with the value "blue"
$qualities["color"] = "blue";

// Get a word from a request parameter called "quality", and store it in $quality
$quality $_REQUEST["quality"];

// Output whichever element of the qualities array the user asked for by name
echo($qualities[$quality]);

// Output the whole $qualities array in a format useful for debugging
print_r($qualities);

// You can't loop through the $qualities array by number or in any particular order because it isn't numerically indexed.
// Instead you can loop through using a special kind of loop called "foreach".
foreach($qualities as $value) {

    echo(
ucfirst($value));
    
    echo(
"... ");

}

// This alternate foreach syntax supplies keys as well as values
foreach($qualities as $key => $value) {

    echo(
strtoupper($key));
    echo(
": ");
    echo(
ucfirst($value));
    echo(
"... ");

}

?>
Last edited by: Dan Michaelson
Edit access: Designer, Sysop

words1.php
<html>

<body>

    <?php
    
        $contents 
file_get_contents("words.txt");
        
        
$contents str_replace("e""EE"$contents);
        
        echo(
$contents);
    
    
?>
    
</body>

</html>

Last edited by: Dan Michaelson
Edit access: Designer, Sysop

words2.php
<html>

<body>

    <?php
    
        $words 
file("words.txt");
        
        
$connectives file("connectives.txt");
        
        for (
$i 0$i 10000$i += 1) {
        
            
$wordNum rand(0count($words) - 1);
            
            
$connectiveNum rand(0count($connectives) - 1);
            
            echo(
"$words[$wordNum] $connectives[$connectiveNum] ");
        
        }
        
        echo(
"... ");
    
    
?>
    
</body>

</html>

Last edited by: Dan Michaelson
Edit access: Designer, Sysop

weather.php
<html>

    <head>
    
        <title>Weather</title>
        
    </head>
    
    <body>
    
        <?php
        
            
// Load the raw XML
            
            
$rawXml file_get_contents("http://weather.yahooapis.com/forecastrss?p=06511");
        
        
            
// Cheat a little because SimpleXML uses a counter-intuitive syntax to parse XML "namespaces", so just get rid of them
            
            
$rawXml str_replace("yweather:"""$rawXml);
            
$rawXml str_replace("geo:"""$rawXml);
            
            
            
// Parse the XML
            
            
$xml = new SimpleXmlElement($rawXml);
            
            
$channel $xml->channel;
            
            
$city $channel->location["city"];
            
$region $channel->location["region"];
            
$country $channel->location["country"];
            
            
$item $channel->item;
            
            
$lat $item->lat;
            
$long $item->long;
            
            
$conditionText $item->condition["text"];
            
$conditionCode intval($item->condition["code"]);
            
$temp intval($item->condition["temp"]);
            
$date strtotime($item->condition["date"]);
                    
        
?>
    
        <p>
            <b><?= $city ?></b> <?= $region ?> <?= $country ?>
        </p>
        
        <p>
            <?= $lat ?> <?= $long ?> <?= $conditionText ?> (<?= $conditionCode ?><?= $temp ?>&deg;
        </p>
        
        <p>
            <?= strftime("%c"$date?>
        </p>
        
    </body>

</html>

Last edited by: Dan Michaelson
Edit access: Designer, Sysop

LAB 4

TOPICS COVERED

  • Writing to and reading from a database

See “Resources” above for a Macintosh MySQL client to explore Ernie’s database server and create tables you need.

MySQL cheat sheet:

SELECT: Retrieves rows

SELECT * FROM weather;

SELECT * FROM weather WHERE zipcode = ‘06511’ ORDER BY date ASC LIMIT 1;

SELECT zipcode, temperature FROM weather WHERE zipcode = ‘06511’ ORDER BY date DESC LIMIT 1;

(WHERE, ORDER BY, and LIMIT are optional)

INSERT: Adds one row

INSERT INTO weather (zipcode, temperature) VALUES (‘06511’, ‘42’);

DELETE: Deletes rows

DELETE FROM weather WHERE zipcode = ‘06511’;

(You can also add ORDER BY and LIMIT clauses)

UPDATE: Changes existing rows

UPDATE weather SET temperature = ‚42‚ WHERE zipcode = ‚06511‚;

UPDATE weather SET temperature = ‘42’, code = ‘7’ WHERE zipcode = ‘06511’;

(WHERE is optional; you can also add ORDER BY and LIMIT clauses)

Last edited by: Dan Michaelson
Edit access: Sysop


database-input.php
<html>

    <?php
    
    
// Choose any city
    
$zipcode $_REQUEST["zipcode"];


    
// ======= GET THE WEATHER FOR THIS ZIPCODE FROM YAHOO ========

    // Load the raw XML
    
    
$rawXml file_get_contents("http://weather.yahooapis.com/forecastrss?p=$zipcode");

    
// Cheat a little
    
    
$rawXml str_replace("yweather:"""$rawXml);
    
$rawXml str_replace("geo:"""$rawXml);
    
    
// Parse the XML
    
    
$xml = new SimpleXmlElement($rawXml);
    
    
$channel $xml->channel;
    
    
$city $channel->location["city"];
    
$region $channel->location["region"];
    
$country $channel->location["country"];
    
    
$item $channel->item;
    
    
$lat $item->lat;
    
$long $item->long;
    
    
$conditionText $item->condition["text"];
    
$conditionCode intval($item->condition["code"]);
    
$temp intval($item->condition["temp"]);
    
$date strtotime($item->condition["date"]);


    
// ======= SAVE THE WEATHER AS A NEW ROW IN THE DATABASE TABLE  ========

    // Connect to the database server
    
mysql_connect("ernie.art.yale.edu""networks""yalent");
    
    
// Select our database
    
mysql_select_db("nt1_2009");
    
    
// Make sure there are no dangerous characters in the user-supplied zipcode
    // (to be safe, you should do this on everything you insert in the database that you didn't generate
    // yourself-- e.g. even the data from Yahoo)
    
$zipcode mysql_real_escape_string($zipcode);
    
    
// Add a new row to the weather table in the database
    
mysql_query("INSERT INTO weather (`zipcode`, `lat`, `long`, `temp`, `condition_text`) VALUES ('$zipcode', '$lat', '$long', '$temp', '$conditionText')");

    
?>

    <body>
    
        Thank you.

        <!-- Would be nice to also give the user some feedback, such as telling them what the weather is -->
            
    </body>

</html>

Last edited by: Dan Michaelson
Edit access: Designer, Sysop

database-output.php
<html>

    <body>
    

        <?php
        
        
// Connect to the database server
        
mysql_connect("ernie.art.yale.edu""networks""yalent");
        
        
// Select our database
        
mysql_select_db("nt1_2009");
        
        
// Get all rows from the weather table
        
$result mysql_query("SELECT * FROM weather");
        
        
// See how many rows there are in the result set
        
$numRows mysql_num_rows($result);
        
        
// Loop through each row
        
for ($i 1$i <= $numRows$i += 1) {
        
            
// Get the next row from the result set
            // The row will be an associative array (an array with string indexes), where the indexes are
            // the column names.
            
$row mysql_fetch_assoc($result);
            
            
$id $row["id"];
            
$zipcode $row["zipcode"];
            
$temp $row["temp"];
            
            echo(
"$id $zipcode is $temp degrees<br />");
        
        }

    
?>
    
    </body>

</html>

Last edited by: Dan Michaelson
Edit access: Designer, Sysop

LAB 5

TOPICS COVERED

  • JavaScript
    • Like HTML and CSS, JavaScript is code that just runs in the browser. You don’t need any PHP for it, although just like HTML and CSS you can also generate JavaScript using PHP on the server, or inject PHP variables into your JavaScript.
  • When can JavaScript code run:
    • In an onclick, onmouseover, or onmouseout attribute of an HTML element
    • As soon as the page loads [best way to do that is using Prototype’s Event.observe(window, “load”, doSomeFunction) method]
    • When a timer goes off (setTimeout and setInterval)
    • Using a JavaScript event handler (made easier by Prototype) to listen for many kinds of events and then do some function
  • Selecting and manipulating an element of your HTML page using the JavaScript functions in the Prototype library, while the user watches. (This is called accessing the “Document Object Model”, and it’s the basic reason why you use JavaScript). You can (although we didn’t try all of these things):
    • Change an HTML element’s CSS style, including hiding and showing the element
    • Change an HTML element’s content
    • Load new content for an HTML element from the internet (this technique is called “AJAX”).
    • Even insert a new HTML element or delete an existing element (although it’s usually easier to just un-hide and hide elements).
  • Prototype selection functions include $(“id”) to select a single HTML element by its id attribute, and $$(“selector”) to select multiple HTML elements using any CSS selector including class name etc, just like in a stylesheet.
  • Animation with Scriptaculous, another JavaScript library (which requires Prototype).
    • Along with animation and transitions (“effects”), Scriptaculous also has functions to enable dragging and a couple interface widgets such as sliders.
    • Internally Scriptaculous creates animation just by using JavaScript timers (setInterval) and Prototype functions to change the “top” and “left” CSS styles.
  • In JavaScript, some things may be asynchronous— specifically setTimeout, setInterval, AJAX requests, and event handlers. That is, JavaScript code execution isn’t “blocked”, rather it continues while the timer is running or the network request is in process. (This “non-blocking execution” almost never happens in PHP— certainly we’ve never encountered it together.) Then when the timer goes off or the network request completes or the event occurs (such as a mouseover), effectively more than one thing may be happening at once.
  • There are also other libraries that compete with Prototype & Scriptaculous, such as jQuery, MooTools, Dojo and the Yahoo User Interface library (and even Jürg Lehni’s Bootstrap). Some are more bloated than Prototype/Scriptaculous, some are less bloated and more elegant, some have lots of great features; but in this area there’s a lot to be said for just settling on one and getting to know it. Prototype/Scriptaculous are well-supported and happen to be integrated into the Ruby on Rails framework, which I use and which you’ll probably use too someday.
  • For what it’s worth, JavaScript itself happens to be a really fascinating and elegant programming language, although the Document Object Model specifically can be a pain (but much eased by Prototype). JavaScript (minus the the browser’s Document Object Model) is also nearly identical to ActionScript, Flash’s programming language. Syntactically it’s also in the same family as PHP (all are descended from C).
  • By the way, After Effects and other Adobe application also allow you to “script” them or write “expressions” by typing in JavaScript code.
  • To debug JavaScript:
    • In Safari, go to Preferences→Advanced and enable the “Develop” menu. Then see JavaScript errors under Develop→Error Console. You can also type in JavaScript statements at the bottom of the Error Console and immediately see what happens (neat!).
    • In Firefox, use the Firebug plugin (does all the same things as Safari’s Develop menu, plus it’s even better— Safari’s Develop menu was inspired by Firebug).

See Resources above for a quick download link for Prototype and Scriptaculous.

Last edited by: Dan Michaelson
Edit access: Sysop


animation.html
<html>

    <head>
    
        <script src="javascript/prototype.js" type="text/javascript"></script>
        <script src="javascript/scriptaculous.js" type="text/javascript"></script>
        
        <script type="text/javascript">

            function moveRandomly() {
            
                // Change the style of the "thing" <div> to 72pt Arial.
                // $('id') is a Prototype function that returns a reference to the HTML element with the specified id
                // setStyle is a method that Prototype adds to HTML elements, which you can use to change the element's CSS style

                $('thing').setStyle({fontFamily: 'Arial', fontSize: '72px'});
                
                // Move the "thing" <div> by a random amount, over 1 second; and when ithat animation is done, call the moveRandomly function again.

                new Effect.Move('thing', {mode: 'relative', 
                        x: (Math.random() * 300) - 150, 
                        y: (Math.random() * 300) - 150, 
                        duration: 1, 
                        afterFinish: moveRandomly});
                        
            }

            // This is a Prototype event handler that calls a function when the page is done loading
            // Call the moveRandomly function when the page is done loading, to start things moving    
        
            Event.observe(window, 'load', moveRandomly);
        
        </script>

        <style type="text/css">
        
            #thing {
            
                font-size: 48px;
                background-color: yellow;
                width: 200px;
                height: 200px;
                position: absolute;
                top: 100px;
                left: 100px;
            
            }
        
        </style>

    </head>
    
    <body>
    
        <div id="thing">Thing</div>
        
        <!-- Do moveRandomly() when the user clicks this link 
             (but note: this is fairly redundant now since we also call moveRandomly above as soon as the
             page loads; in practice you'd want to do just one or the other) -->

        <a href="#" onclick="moveRandomly();">Do something</a>
    
    </body>

</html>
Last edited by: Dan Michaelson
Edit access: Designer, Sysop