[ Silence ]
>> Alright, welcome to the end of week 8 and to Halloween week.
So a couple of announcements, there will be another lunch
with David and TF, NCAs [ph] next week.
So we have dinner on Wednesday at 6 pm in Mather.
We will be joined by a couple of Computer Science faculty,
who will be there just to chat up students,
talk about their research and just generally have a nice meal.
Lunch next Friday as well, if you can't make this,
although you are welcome at both, just head to CS50.net/RSVP
and do you mind taking the house audio down just a little bit.
Alright, so I got a little tired of being yelled
at every time I went to our own home page, so now we have muted
that and we now just have thanks
to a wonderfully fun language called Java Script,
these flying ghouls on the screen.
So you will soon now how to do silly things like that,
but it is around office hours in P Set 6 so it is
around this time every semester that students,
especially those less comfortable
who are feeling a little overwhelmed since things seem
to have accelerated, the problem sets are getting larger and sort
of less byte size and realize that this is to be expected
and this is by design right, because the goal
of the course ultimately is to make sure
that you guys can stand on your own at the end of the semester
and don't have to be handed for instance a P set spec
to actually solve problems and get work done.
But with that said office hours,
which are actually wonderfully being taken advantage of early
in the week enough so that we now will try
to divert some resources to earlier in the week
since finally the lesson seems to be thinking in.
We realize that office hours
in the science center are not the most nurturing environment
when you are kind of struggling and you have questions
that are more conceptual than they are sort
of deal breaking single lines of codes with bugs.
So do realize that on the staff page of the course's website,
we had 60 names and 60 email addresses,
all of whom would be happy to sit down
and in fact would enjoy sitting down on a more one to one basis
and answering questions, working through things with you.
Certainly myself, if you have a friend on the staff
or just friendly with someone, email them directly.
If you are feeling that you would really benefit
from some more one on one attention.
And also email heads@CS50.net if you would like to be introduced
to someone who could sit down with you one on one.
So take advantage of that, plenty of time remains,
don't feel like office hours are your only recourse
and also a word on how to tackle these things.
So early on, Mario was so fairly bite size
and it might have taken you some time to actually get
that pyramid working, but it was kind
of clear what you needed to do.
You needed to use one or more four loops
or Y loops and make a pyramid.
Now you are being handed a lot more code
and you are being asked this more sort of higher level
of idea of implementing dictionary and a spell checker.
But realize that even though the P sets have gotten bigger,
there are still lots of bite size problems in there.
So if you are having this reaction even after watching
or attending walk through that you are still not quite sure
where to begin or Marta has given you a whole lot of hints
and tidbits it seems, but you are not sure how to assemble all
of these puzzle pieces.
Well just take a step back and look through the P set spec,
they are designed with check boxes intentionally
so that you can consider for P set 6 the following work flow.
So you have got essentially four things to do, load,
unload, size and check.
So you can't really do unload first,
can't really do size first,
because you don't have anything to count.
So that leaves load and check, alright so between those two,
probably want to implement load first
so that you have something to check.
Alright so now load that alone might be kind
of a daunting task, you might have some general idea
that you want to implement a hash table or tri
or something else, well again and this is not meant at all
to be diminutive, take baby steps.
Literally sit down with that function and add that line
of code to F open and open the dict file
that you have been passed and don't even try reading it
into memory perhaps, just try iterating over it,
as Marta hinted in the walkthrough with F get C
or F read and just do something simple like count the number
of words in the dictionary and at the end
of your load function, just call Print F, print that number
and compile, run it and see
if your number matches what the P set says you should get.
Now granted, you have just written a few lines
of code that are not useful.
You are going to throw them away,
but at least now you have hit this milestone
where you can feel like you are making forward progress.
And again, this notion of baby steps is something even I quite
honestly today practice and without going
into specific details, because they are not
that interesting even something like the stupid twitter site,
I mean that is kind of a big problem.
Silly though it is that has all these little pieces
and what I did that night in my hotel room was sit down
and think alright, I need somewhere to store these tweets.
Alright, so I need a database.
What do I want this thing to look like
and we will talk about that today.
I now need, once I have my database,
I need to import this data from Twitter.com.
Let me figure out how to just write a little program
that queries Twitter, grabs the data and puts it
in to my new database.
Now at this point, my program is still useless
to the outside world.
You can't see any of these tweets
and so then I began writing a webpage
and I figured out the layout.
It looked basic.
There was no actual content, but I had the structure
and I had words like content will go here and then I saved it
and that was another sort of milestone or baby step.
And finally did things finally start coming together
at the very end when I had something working.
So realize if you have started to take this approach or got
into this habit of trying to sit down and do the problem sets,
it is not a very good approach.
Try to bite off little pieces of the problem set,
even if you define your own milestones for yourself
and then you will feel I think that you are chipping away
at these things and you will be surprised actually
when you realize wow, I just have two blanks to fill in
and what seemed like a big task was actually just a bunch
of little Mario like problems.
So keep that in mind, even if you are taking advantage
of office hours, walkthroughs and the like.
Alright, any questions on anything thus far?
Alright, so we left off on Monday talking about web pages
and we did a little bit of HTML and I showed you how
to make really ugly web pages,
but the general structure of a webpage.
A webpage has an HTML element at the top,
you have got a head element, inside of which can go the title
and this other stuff called CSS and then you have the body,
which is where the guts of your page goes.
And inside the body, you actually put the words you want
to appear on the screen.
You put tags for images and hyperlinks that you want
to appear on the screen,
so all of the interesting stuff happens in there.
But everything we did on Monday was very static.
If you visit that webpage today, it is going to look the same
as it did on Monday, because there is no dynamism.
There is no user input.
There is no automatic fetching of data from Twitter.com
or anything that changes over time.
So it is kind of a boring website.
This is the sort of website 1995 style,
so thankfully there is a number of languages
and tools these days that allow your websites
to be much more interesting and useful
and actually change over time.
I mean case in point, Facebook.
Facebook is interesting because it changes constantly
and it is not Mark Zuckerberg there editing HTML files every
time a change is made to the site, it is all driven
by scripts and programs and databases.
And that is what you will get after this week and next
in the next two problem sets.
So this stuff, I frankly think is a whole lot of fun,
because finally now that you understand
or almost understand how things are working underneath the hood
with C and Rem and all of that finally now are we going
to equip you with some higher level tools, as promised Monday,
so that you can solve interesting problems more easily
and with the right tools.
So here is a simple example to motivate where we will go
with P set 7, so once upon a time I realized
that Yahoo Finance which looks a little
like this let's you get stock quotes and all
of that information and I searched for something
like Google, which is already back
at like 500 dollars a share.
Alright, so I click Goog, which is its stock ticker symbol
and then in the top leftish here under last trade,
this is its current price.
Okay so that is kind of interesting
and I could write a program to screen scrape that content.
I could go into the HTML,
so the number I am looking for is 540.65.
So let me go ahead and copy that let me go ahead
and view source in my browser.
I am going to do Control F here to try to find it.
Let me do this, oh I didn't quite copy it correctly,
so 540.64 uh huh, 63, it already changed.
Alright, so there it is, somewhere nested inside
of this page, inside of what is called a span tag,
inside of a small tag or inside of a T. there is a whole bunch
of stuff surrounding this, so what this means if I wanted
to screen scrape this thing, I am going to have
to write a program that understands all of this content.
So already, there is this tension between what is so easy
for a human, copy/paste kind of wins here, it is so easy
to do with your mouse.
Well that is not going to work if you want
to implement this kind of functionality
of fetching stock quotes for an arbitrary webpage or any number
of stocks throughout the day.
We need to automate it somehow, so testament to the ease
with which one can do this, let me go ahead and whip
up a little program called quote.PHP.
So I am going to use an extension called PHP,
because it is no longer in C. Every PHP file that we will do
in the class must start with these two tags, open bracket,
question mark and question mark closed bracket, this is a hint
to the PHP program, which you will see in a moment
that tells it here comes some PHP code.
And the reason for this is
because open bracket question mark is not a valid X-HTML.
There are no tags that we saw Monday that start
with a question mark, they all started
with alphabetical letters.
So this helps distinguish one from another.
So it turns out that PHP is very similar syntactically to C
and this is a good thing, because it means even you guys
with just a few weeks of C behind you can actually leverage
that knowledge and learn this new language.
So I want to fetch that URL, so let me go ahead and I don't want
to screen scrape this, so notice what I have
in the top here is this URL, but notice this, there is this link
over here to download data and it is a little small.
You won't really be able to see this just yet, but down here
if you hover over a link, I see the actual URL that link goes to
and it is called quotes.CSV and if I click this link,
download data, what is need is that it triggers this pop-up
and it is saying how do you want to open this.
Well CSV file comma separated values, this is just a text file
that you could have made with nano or notepad
and it just has a bunch of different fields,
each separated by commas.
So let me go ahead and save this to my desktop, quotes.CSV.
Let me minimize this, minimize this, here it is here.
And I am actually going to go ahead and let's go ahead
and open it with notepad,
which is just a simple Windows application.
Let me go ahead and open this file,
which is called quotes.CSV and that is it.
This is all I downloaded from Yahoo.
It is a comma separated values file,
because look all the interesting fields of data are separated
by commas and you can kind
of infer what some of these are, right.
There is the stocks in bullet top left,
there is the current price, changed a little bit.
There is the current date, the current time
at which we fetched it and then some other information,
like maybe the day's high and low
and these kind of financial numbers.
So for now, I don't really care about those, but I do care
about this guy at the start, 541.166.
This is the current stock price.
I want to write a little program in this new language PHP
that fetches me that piece of data.
And what is need about CSV files incidentally is
that if you typically double click them
or explicitly open them with something
like Microsoft Excel they mimic the idea of a spreadsheet.
Because the commas delineate to the actual columns,
there aren't more than one row here,
but I have opened this same file in Excel and so what I kind
of have here is a sort of mini database
that I have downloaded from Yahoo.
So this is a very nice thing,
because now that you will have programming chops with PHP
and with internet connectivity, you can actually query data
that is machine readable, because it is so much easier
for us to read or parse so to speak this than that mess
that was the whole actual webpage written in X-HTML.
So let me go back to my command line and I am going
to do something fairly simple, I am going to say alright,
the URL I want to fetch is you know what let me go ahead
and just copy that URL from Yahoo's site.
So I am going to right click on it this time,
copy link location, I am going to go back
to my terminal window and paste.
So I am declaring a variable here called URL.
I am making it an uppercase, because it is kind of in my mind
like a constant, at least for now.
I am keeping everything inside those braces.
It is wrapping, which is a bit ugly, but that is just the URL.
So now I am going to do a little syntax that is familiar
from C. There is an F open function and PHP is neat,
because you don't have to pass it just a file pass
on the local hard drive.
You can actually give it a URL.
Don't try this in C, bad things will happen, it just won't work,
but the syntax here is pretty much the same.
I am going to open this URL in read mode
and now I have a file handle or file pointer,
synonymous in this variable called FP.
So that is one of the few syntactic differences thus far,
variables in PHP start with dollar signs,
but there is no data type.
I haven't said string.
I haven't said int.
I haven't said anything, so this is one upside and maybe downside
of PHP, it is a little looser with data types.
You really don't have to think that much about them.
So now I am going to do this,
there turns out there is a function
in PHP called F get CSV, file get comma separated values.
What is neat about this is that I can pass to this a handle,
the file handle that I want to read from FP.
I can then close my parentheses here and then what I have
in this variable called row are the contents of the first row,
but what is really neat about this particular function is
that it does the printing of, it does the parsing
of that CSV file for me.
So what do I mean by this exactly, well let me do this.
Right now I have a variable called row,
it is storing the contents of what I just read from this URL.
I am going to use this function, Print R,
which is print recursively that row.
I just want to do a quick and dirty check here.
So this is again an example, I am writing a code,
I am about to throw away, but it is a useful sanity check.
So I have saved my file, I am now back at the prompt
and I have a file called quote.php,
which lives right here.
PHP is a little different from C in that it is not compiled.
PHP is an example of an interpreted language,
which means to actually run it you have to pass it
as input to another program.
Now on a Linux computer, this program is called PHP.
On a Windows computer, it is called PHP.exe.
On a Mac, it is called PHP.
So I am going to run a program called PHP,
which is an interpreter, a program that someone else wrote
that is going to read my code, top to bottom, left to right
and do what my code tells it to do.
That is what it means to interpret.
So I am going to run PHP on quote.php and hit enter
and what I see here is oh interesting,
now this is kind of a debugging trick.
Think of Print R kind of my Print F when I am debugging.
It is printed what data type apparently?
In array, so it says in big keyword there, array.
So it turns out that F gets CSV actually analyzes that CSV
that comes back from the internet,
it realizes oh there is commas in between all
of these pieces of data.
Let me create for David an array of the appropriate size,
size 9 and let me put in each of the locations,
each of the fields from this Excel file, from this CSV file.
So what Print R does, Print recursive, it is just kind
of a debugging trick here.
It is showing me the contents of this variable called row.
So which index location do I care about in a moment
when I want to just print the stock price?
So just the first one, one, so let's see
if the syntax is pretty similar.
So I now have in memory a variable called row.
It is an array.
I didn't have to do any of that nastiness
with declaring the size of the array in advance.
I didn't have to use [inaudible] and here is one of the upsides
of a language like PHP, which is also known
as a scripting language, which generally in spirit make a lot
of these painful details go away and they do them for you,
all be it at some costs, which we will discuss.
So let me go back to my program.
I don't want to print the row.
What I want to do literally now is print that field.
So print, what do I want to print, row bracket 1
and then I am going to have to print a new line I think.
So let me do print new line
and you will typically use the print function,
as opposed to print F, but Print F does exist in PHP.
Let me re-run my program and waa-laa,
now I have the stock price of Google.
Alright not bad, but not all that useful,
I now have a program that just checks a webpage
that I could check myself with a browser,
so let's make it slightly more dynamic.
Let me go in here and notice this part of the string.
Notice at the very top of my URL, there is this parameter.
So we talked very briefly on Monday about this
when we reimplemented Google.
When I implemented Google, I just had to pass
to Google a special parameter.
What was the name of that parameter that Google used
to search for content?
>> [Class answering]: Q
>> So it was just Q, so the URL for Google,
followed by question mark, which said here comes some parameters,
then the name of the parameter Q an equal sign and then the value
that I typed in, so whatever key word I was looking
for like CS50.
Well here, it looks like Yahoo has the same trick going on.
They have some long URL ends with quotes.csv, question mark
and there is where it starts to get interesting,
S which is symbol probably equals GOOG
and that is what I typed in.
Now at first glance, I actually don't know what the rest
of this URL means.
It is wrapping on to two lines, so let me just move it
for a moment onto a new line.
I don't know what this nonsense is after Goog.
I do see that there is an ampersand
and an ampersand is what delineates one parameter
from another.
So the ampersand says done
with first parameter, here comes another.
The second one quick, quick sanity check, is called what?
So it is F, turns out after a little Googling
that is a format code.
So what F equals is this long crazy string of characters
and essentially Yahoo has a little cheat sheet that says
if you want the stock symbol pass in this format string.
If you want the day's high and the day's low,
pass in this format string.
So it is like Yahoo's proprietary version of F print
out or print F strings or format codes.
So I actually don't really care so much about that,
because clearly this URL works and gets me the stock quote
and some other stuff, but I just want to make this dynamic.
I want to factor out the Goog
and not make this a hard coded value here and I instead want
to do something like dollar sign symbol.
So let's see if I can now define a variable called symbol
so that I dynamically get a different URL based
on the input.
So it turns out that PHP has a variable symbol gets RV
bracket 1.
So I have command line arguments in PHP 2, so this is going
to get RV of 1, my first real word after the program's name.
It is going to put in a variable called symbol.
This line of code here, very interestingly is going
to create a string, most of which is static,
but then because I have this variable in the middle
of my string, what is really nice about PHP
and this dollar sign notation is it will do a substitution right
there for me.
There is no messiness of copying strings
and concatenating them together using re ad loc
or stir copy all of this mess.
It all goes away and it is much more user friendly now.
So now if I do a little sanity check, let me go down here
and again in the interest of baby steps, milestones
and what not, let me just do a quick check.
Let me print the URL.
Alright, so you know what, let me exit.
I don't want to even see what happens next just yet.
I want to make sure my URL is correct.
So I am going to run PHP of quote, PHP and just
to underwhelm, I am going to run it on Goog.
So it looks like, if I zoom in, it generated the right URL.
But what is need now is if I re-run this
with MSFT, I get Microsoft.
Notice now it has been substituted in
and if I do something like Yahoo myself,
YHOO, I get a Yahoo string.
So now it looks like I have the framework
for a command line program that will just spec stock quotes
for me on demand, any symbol that I actually want.
So let me get rid of this temporary code.
Let's see I open the URL in read mode.
I get the first row of the file.
You know what I don't actually need this.
I am going to do F close of file pointer now,
because I don't need that file handle anymore once I have read
it into memory.
So now I can just print the row it looks like.
So let's see, let me go ahead and save this, run PHP of quotes
and let's do Goog again.
Here we go 541.58.
Now let's do MSFT, 28 dollars and Yahoo, alright,
so now I have in what five minutes time
and we are not talking 30 seconds time a little program
that fetches real data from Yahoo Finance,
a website that lives who knows where on the internet.
It grabs it and it shows it to me.
And I could do any number of tricks to this data.
This is a very simple program, but this is what is powerful.
I challenge you to implement this in C
in just seven lines of code.
So this is where it starts to get exciting to be honest.
So let's actually now pause for any questions, any questions
about that quick and dirty command line example.
Okay, so it is neat right, but you don't want to really have
to tell your users or your family
and your friends oh you have to download putty and then SSH
to cloud.CS50.net and then run this esoteric command just
to get a stock quote.
Right, the web is kind of a lot more
in vogue then SSH these days for normal people.
So just as years ago.
[ Laughter ]
It is kind of true.
So just as years ago, I faced this problem with the frosh IMs
that wanted to deprecate pieces of paper and replace it
with the web, well today to, the web is kind of the place to turn
when you want a generic user interface, but you want
to be able to create dynamic output.
So what is nice about PHP is that just
as we can write command line scripts, command line programs
that we can use for quick and dirty things, for research,
for course administration, just for our own geeky self interest,
we can use the same language now to spit the output not
to my black and white screen, but to an actual webpage.
So enter in a web based approach.
Let me go into now some of the code
that we gave out the other day.
So I am going to go into my public HTML directory
and I am going to go into lectures and I cleaned
up my code, so the paths on your printouts are a
little different.
I ended up having so many files that I put everything
in this Frosh IMs directory.
So my goal now is to implement something like this.
I am going to go away from Yahoo Finance,
more on that in Problem Set 7.
I am going to go to Cloud.CS50.net/~
and again this tilde notation is very common.
If you have an account on a shared server,
very often can you access your webpage using this tilde
notation and I am going to go into /CS50/lectures
and now this is a generic output.
What is nice with most web servers,
if you have no HTML content there,
it just shows you the contents of the directory,
if you have configured your accounts for this.
So I am going to just click my way to what I want.
Oh here was our nastiness from the other day,
let's see if we can't improve upon that guy.
Let's go into the Frosh IMs directory
and go to number one here.
So essentially, this is all I wanted to implement is
like a sophomore in this language called Pearl,
this was an improvement over the piece of paper and the trek
across campus to register for Frosh IMs.
Now we gathered a little more data, but I chose these examples
for today, because what we have here are some basic
form elements.
And you have used these on any number of websites.
This thing up here is a text field.
This thing down here is a check box.
This thing here is a radio button
and notice it is exclusive.
Once you click one, the other one gets unchecked,
where check boxes are just on and off independently
and then you have these drop down select menus.
So this is kind of a nice self-contained example,
because it illustrates most
of the popular interface mechanisms.
And to be honest, if you think about almost any website
that you visit today almost all of them boil
down to these terribly, terribly simple user inputs.
You might have felt limited in C with get in and get float
and get double, but in the web, you really kind
of have the same limitations.
You have a palate of four or five user input mechanisms
and the whole web has grown up on that basis.
So my goal is to allow people like freshman to type
in for instance John here, John is going
to be a captain, a male and Matthews.
And when I click register, I want something
to happen to this data.
Well first, let's take a look
at how this actual page came into existence.
This is Frosh Ims 1.php and let me first disclaim
that even though this file ends
in .php there is actually no dynamic content
in this particular page.
So .php is the convention that people use,
even Facebook uses this for a lot of its pages,
that means here comes some PHP code.
Now it turns out for this very first simple example all I have
at the top of this file
in between those special PHP brackets are some comments.
So it is really not doing much at all here, just to be clear.
So the real stuff is happening down here
and this is the stuff called X-HTML.
So this is the thing that at least I have not remembered
for 10 years, I just copy
and paste it every time I make a webpage.
Then I copy this first line
and then the training wheels come off
and I can start coding things by memory.
So inside of this page is a title called Frosh IMs,
then I have the body of my page here
and then there is this thing called div.
So web pages have things called divisions and you will get used
to this if you play around.
I did this in different ways on Monday.
There are many different ways to implement web pages,
so don't think there is only one way to achieve something.
That is kind of the fun of it.
So I am using some slightly new tags.
Div means here is a division, put this block of code
in the middle of the page.
H1 we saw it is a heading tag, it means make it big and bold.
BR, BR means line break, line break.
Form means here comes an actual form.
Action is an attribute, so notice next
to the word form action,
that means where do you sent the contents of this form
and method finally can be for our purposes one
of two things, post or get.
If you want the information to be sent to the server in the URL
in kind of a long cryptic looking URL, you use get.
If you want to hide that information for privacy reasons
or snooping or whatever, you use post.
And there are other reasons as well, but for now,
it is an easy copy/paste.
So now I am using this trick, it is a little bit retro,
but still frankly very simple.
I am going to change one thing.
It turns out I am using a table to lay out this page
and you can kind of guess where the table is.
I have kind of got four or five rows, because each
of these inputs is in a row.
Then I seem to have a nice column, because I was kind
of anal and I wanted all of the words like name, captain,
gender, dorm to line up.
So I kind of have a grid here.
So I am going to change the attribute on my table tag
to be border equals one, instead of zero,
which it was a moment ago.
I am going to save my file and I am going to reload this page
and now you see the table.
Now if I turn this table on,
if I had left the border it really looks bad.
So I decided it looks a little better to hide this table,
so we use this on CS50's website
and this is not an uncommon approach even these days.
So it is kind of nice, quick and simple.
Alright, so how did I create this form.
Well we did a little bit of this for Google.
Let's see I have first of all, oops,
we have let's see the word name and it turns out to create rows
and columns in tables, you use things like TR for table row,
TD for table data and I want dwell on these details here,
because it is easy enough to tinker
and realize what it is doing.
I cannot emphasize enough, just as I did in the basement
of the science center years ago, the best way
to use this stuff is to experiment.
If you are not sure what something does, delete it,
see what happens, see how bad things get and then put it back
and then you understand what that line of code did.
Alright, so here is name and look here is the text field,
input name equals name, type equals text, alright.
What about this?
Here is captain, same idea, input name equals captain,
type equals check box.
Down here we have two inputs,
because I have two possibilities per user,
input name equals gender, type equals radio, value equals F
and then I literally write an F here outside of the tag
so that the user actually sees what the value
of this attribute, what this button is.
and then same deal for male here, I have the same thing,
input name equals gender, type equals radio,
but I have a different value here and I label it as M,
but I could label it anything I want.
And then finally dorm is pretty self explanatory too.
It is longer because there is more stuff,
but it is select name equals dorm, size equals one.
That just means show only one at once, don't show them all,
just give me a drop down menu and then this blank one here,
this first option means leave it blank by default.
It looks a little weird if Apley Court is the default,
I would rather it be blank then Apley Court,
just for aesthetics.
And then down below, I have option value equals something
and then inside or outside of the tags,
notice this distinction.
So there is this distinction in X-HTML which is really useful,
a form element can have a value,
but aesthetically it can say something different.
So this is useful, so that you can pass
in for instance numeric values, but actually label them
with something more user friendly.
So there is this distinction, I kept it simple,
they are both identical, but that is not always the case.
And then finally there is only one last input
to achieve this functionality.
At the very bottom, I have input type equals submit,
value equals register exclamation point
and that syntax is what gives me this button
with precisely that label.
So that is all it takes
to create a user interface using X-HTML
and relatively simple form input,
unfortunately the problem we ran into on Monday
when I clicked submit the first time with Google,
it went nowhere, because I hadn't implemented the search
URL, the backend functionality.
So I tweaked my action line and I sent the form not to myself,
but to Google.com itself and that solved
that problem, but that is fine.
That is all fine and good.
Now we need to start pulling our own weight here,
so let's implement our own registration feature
on the backend.
Let's see what happens by default.
So I am going to register John and Matthews
as a captain, click register.
You are registered.
Well not really, alright well let's see what really
happened here.
Let me zoom in.
Notice at the top of this file it says the URL has changed,
it was Frosh IMs 1.php, now I am at register1.php,
because my Frosh IMs 1 file submitted via the action
attribute to this file.
So that was sort of origin, now I am at destination.
So apparently this file,
register1.php is registering the user.
It is emailing that proctor in Wigglesworth
or it is recording it in a database or something.
Well let's take a look.
I am going to now open register1.php,
which you also have a copy of.
Let me scroll down, come on, come on.
Any questions?
[ Laughter ]
Come on, plan B, there we go.
Alright, now it is color-coded, so let's take a look here.
Alright, it looks like I do have some PHP code
at the top of register one.
Let's come back to that in a moment, most of it is comments,
but there is some interesting stuff there.
Let me scroll down, oh this is kind of a cop out.
All I did for the resulting page is I spit
out you are registered, well not really.
So the code must be up top so let's see and this is okay.
So notice now what I have done for the first time,
I now have PHP code inside of a file that also has X-HTML.
So this is one of the upsides of using something like PHP.
You can comingle PHP code in logic
with actual raw content anything
in between the open bracket question mark
and the closed question mark closed bracket means PHP the
program, the interpreter that I ran before,
you deal with this part and what PHP's purpose in life is
which we saw at the command line is just
to produce output, to spit out text.
In my very simple stock quote program,
I just spit out the stock price, but there is nothing saying
that I can't spit out X-HTML, right.
If I really wanted to be clever, let me go back
to my quote program, recall it just looked like this.
Looks like I have the power to print anything I want,
so technically I could do something like print HTML,
print head, print and so forth, this is all it takes
to start generating web pages dynamically,
just generate via print or similar calls the actual X-HTML
and content you want the browser to see.
So this was a command line script,
my quote program now I am doing something inside
of my web directory, public HTML, but the idea is the same,
anything I print will show up on the browser window and not
on this black and white screen.
So what logic am I doing?
Well very common case with form submission is you have
to validate it.
Right, you don't want garbage going into your database.
You don't want spam.
You don't want non-existent usernames
and passwords and all of this.
So a very simple way of checking what the user has done is
with some conditions.
So in PHP we have ifs and else's and fors and whiles and all
of this stuff, so notice what I have done here.
And it wraps a little ugly, but notice what I have done.
If dollar sign underscore post bracket name, so it turns out
and this is a real convenience in this particular language,
any time a user fills out a form
and that form used method equals quote unquote post,
everything the user typed in on the webpage is sent from point A
to B from browser to server, but then it is packaged
up really nicely inside of an array.
And that array is called dollar sign underscore post,
stupid name, but it is all in there for you,
which is really nice because using square bracket notation,
I can then access the name of any parameter that was
in those forms and I had a few parameters.
I had name, I had captain, I had gender, I had dorm.
So if I want to check if the user typed anything
in for their name, I simply ask
if dollar sign underscore post bracket quote unquote name
equals equals nothing, quote unquote that is bad.
I want to redirect them back and have them do it again
or if they fail to give me their gender,
I don't like that either.
I am going to reject their input
or if they gave me a blank dorm equals quote, quote,
I am going to reject their input.
So this whole if condition has three clauses, if no name
or no gender or no dorm, what do we do?
Well a little trick in PHP is if you want
to redirect the user elsewhere,
you call a function called header
and you specify location colon and then the URL
that you want to send them back to.
So had I not behaved well here,
had I been to this registration page and I said you don't need
to know my name, I am just going to show up and I am going
to click register, nothing good happened this time.
I got redirected back to the page presumably
so I can reenter the input.
Now good websites would actually say hey no name,
you need to give us your name.
I have no feedback here, no error messages,
so it is not perfect, but it at least rejected the user's input.
Unfortunately did I actually register the user in any sense
if they do provide legit values?
No, I just kind of tell them that they are registered,
but really nothing happens with it.
So let's take things up a notch and actually register the user
and you know I don't really know much about databases yet,
so let me take a look at,
let me take a peek at version 4 of this.
So 4 is, let me see, do I want to do 4, no let me see 5.
Come on where is the one I am looking for,
it is next to itself.
I can't remember my own numbering scheme, okay, damn it.
Oh right, I am looking in the wrong place, sorry register 3.
We didn't need to get that high.
Alright, so let's take a look at this one Frosh IMs 3.
It is actually going to look almost the same, so let me go
to Frosh IMs 3.php, form is the same
and let's do a quick check at the code.
This is Frosh IMs 3, if I scroll down, scroll down,
the only difference in this code is
that I change the action line to go to register 3.
So I tried to number these things so that they line-up
so that when you read it over on paper,
you can see which corresponds to which.
So register 3.php is the destination,
but the form is exactly the same.
There is really nothing different here.
So let me quit this and let me open register3.php.
So let's see I took a slightly different approach,
but my goal now is let's actually solve this problem
of registering users.
Well I didn't know much about databases in 1996
and frankly the proctor didn't really know much
about databases, so it would have been overkill
to use a database.
But this proctor did use email and a reasonable upgrade
from pieces of paper underneath their door was send them an
email that they can then filter and keep track
of registrants that way.
That was an improvement, not perfect, but better.
But it turns out that languages like php make it really easy
to do things like send email.
So in this version of register, notice the very top
of the file is just a bunch of comments inside
of the open bracket question mark,
but then I do some sanity checking.
If the name field in post does not equal empty
and the gender field does not equal empty
and the dorm does not equal empty,
so I chose a different syntax just to illustrate
that you can use ampersand, ampersand.
You can use not equals, so I have changed the logic to say
if none of these fields are blank that is a good thing.
Let's proceed to send an email.
Well what email do I want to send, well let's create
on the fly here a little variable called two
and I have hardcoded in my email address for demo purposes,
but I would have put the proctors here years ago.
Subject line is going to be registration,
body is going to be the following.
Now body, I wanted to just put the contents
of the registration.
It doesn't need to be beautiful, but it did need
to be a few lines long, so the email was not one long string.
So I did this trick, body equals this person just registered,
black slash n, black slash n, which does enter, enter.
Now notice this, what do you think the dot operator
does here.
Dot, so this is concatenation, so if you ever thought
about trying to take a string in C and append it
to another string in C, it is a real pain in the neck.
You have to allocate a RAM
for it using Ma-lock or the equivalent.
You have to use Stir Cat for string concatenation.
It is a whole bunch of steps to do something simple in PHP,
in Java Script, in Pearl,
in lots of these higher level languages there is a
single operator.
Dot means take this string between quotes and concatenate
with the next string between quotes.
So this is just my nice pretty printed way
of creating a multiline string all inside a variable
called body.
So what am I putting in this email, well this sentence,
this person just registered.
Then I put the person's name, then I put whether
or not they are a captain, then I put their gender,
then I put their dorm, then I put a typo
and then I put a semicolon and that ends the string.
And then finally I have to add this in PHP and I know this
because I read the manual for PHP, a header is variable
that tells the email who it should come from.
Notice this subtlety here, this is sort of a legacy thing
from email and from Windows and Dos, back slash R,
back slash N. It means carriage return, end new line.
They are slightly different ideas
for now just assume you have to do that.
And then finally, PHP has a function.
It is called mail.
It takes a two field, a subject field, a body field
and then these headers and you know what when you get
to the semicolon it sends an email.
Now again, I challenge you to do something like that in C
without a whole bunch of lines of code.
So let's see if this works and let's cross our fingers
that email is actually reliable.
But notice I have my else now if the user failed
to give me a name or a gender or a dorm, I reject them,
I bounce them back to Frosh IMs.php, but notice this.
If I send the mail, I don't redirect the user upon success
to another URL.
This code that we just discussed executes,
that is the else condition does not execute,
so PHP continues on its marry way.
It has not seen the command exit, so PHP continues reading
and reading, PHP sees oh here is the end of the PHP portion
of this file, so what does PHP do now well
if the PHP interpreter encounters just raw x-HTML
or graphics or images or rather email addresses
and all this it spits it out literally.
It just dumps it to the screen unprocessed.
So to be clear, this open bracket question mark is a
directive to PHP saying here is code that you need to analyze
and execute, the rest of this is just fluffy X-HTML
and static content, but I have comingled them
and that is just kind of nice and convenient here.
So fingers crossed, I am going to go into the form here.
I am going to register John again,
I am going to do a captain mail in Matthews and I am going
to click actually let's do this in advance.
I am going to go to my mail account, alright.
I am going to log in here to my Gmail like inbox and oaky
so I have got no mail, no friends,
no mail at this particular account.
So fingers crossed, click register,
okay you are registered really, so that code seemed to execute.
Now fingers crossed or otherwise this would be the most
disappointing demo today, let's reload, oh it worked.
So I got an email now from me because I sent it
to myself saying this person just registered
and this is literally all the Frosh IMs registration was
in 1996.
It was different language, kind of a different interface,
but we just emailed the proctor this
and this was a huge leap forward and relatively easy just
to reinforce all it took to make that functionality happen,
which is arguably pretty useful for almost any student group
on campus that just needs sign up for something.
It took a few lines of code.
Let's take a five minute break.
Okay, alright we are back.
So that was a lot of new stuff.
So let's just paint a complete picture here.
So the first example I did was this stock quote program
and I wrote that as a command line program,
so I had to explicitly tell my shell, my blinking prompt how
to interpret this code.
And that is why I wrote PHP space and then quote.php,
but clearly I have not been doing
that for the web interaction.
Well it turns out one of the features provided
by modern web services is the ability
to interpret other languages besides just X-HTML.
Typically, a web server's purpose in life is to take
in a request via URL, look
at the file name and it is foo.html.
It finds foo.html on its hard drive and then it spits
out those bytes back to the internet
and the browser displays them per Monday's conversation.
But in this context, the web server needs
to do a little more, the web server needs
to actually analyze the file like Frosh IMs 1.php,
look for open bracket question mark and convert any of the code
in there to raw textual output.
In any words, if there is any print lines,
it needs to send those strings to the browser in addition
to any of the static content.
So this is long story short, a simple configuration issue.
If you run your own web server,
if you are a system administrator with a server,
you can simply configure your web server software,
it is often called Apache or IIS although there are others,
you configure your web server to know that .php files,
if you ever see a URL with .php, make sure to pass it first
to PHP.exe, the interpreter or the equivalent,
get back the results and send the results
to the user's browser.
So there is a bit of a middle man process there in the form
of this interpreter, so in fact serving
up PHP content is actually less efficient certainly
than spitting out raw content
and in fact we will see probably next week
that implementing programs in PHP and higher level languages
like it often is so much easier for development
and it just gets the job done fast,
but not necessarily very efficiently.
You will see and I will be able to implement,
I probably shouldn't tell you this, but I will be able
to implement problem set 6 in essentially one line of code
of PHP on Monday and that is great if not frustrating,
but its performance will suck.
It will take much, much longer to run
than your C based implementation.
So there is actually a reason
for teaching the lower level details,
it will actually serve you well, realize even as you start
to take for granted certain features,
certainly a smart person and a computer scientist,
as opposed to just someone who has some programming background,
you will understand the nuances of picking this algorithm
or this data structure or this language or that and again
that is one of the goals here.
Now an interesting question came up during break,
which was what is to stop me from saying this is not
from myself, but say our own head teaching fellow Jen
[inaudible] did that.
Well nothing, so let's go ahead and register
and in fact let's say in fact dah, dah, question mark, uh huh.
How about hmm, well what is something,
I have nothing funny here,
so this is not really from Jensu [ph].
Alright, so I have pended a stupid string there,
but I have changed the from URL, the from value there
in the header, so let me save this,
let me go back to my webpage.
Let me go back to the form, let's go ahead
and register not John, but Sam, click register, okay.
You are registered really, let's go it is already there.
Oh thank you Jensu and here we have a message
from idadatfsa.harvard.edu.
So now so easy to do, don't do it, so technically doing things
like this within Harvard's campus is
against the ad board rules and all this.
I learned the hard way freshman year when I did this.
[ Laughter ]
No, I actually did stupid freshman.
And I had forged an email,
we had some stupid banter going back
and forth among our proctor group and I decided to chime
in on behalf of someone that I disagreed with,
so I thought I would change his opinion, really bad idea.
[ Laughter ]
And like an idiot, I was using a mail program
that automatically appended to the bottom
of all my email my signature, DJM.
[ Laughter ]
[ Applause ]
Anyhow, not so bright, I was caught so don't do this.
Don't do as I do, do as I say, anyhow.
So it is that easy, but frankly you can spend a whole course
talking about how the internet works
and why actually this is very reasonable
that it is that easy to do.
There really is no authentication
when it comes to email these days.
So let's take a look at the slight variance
of that first example.
This is Frosh IMs2.php
and remember this first example was pretty lame,
because if I made a mistake I was not so much
as even informed of it.
I was just sent back to the original page,
which makes me feel like the website is broken,
not my own input.
So let me try again and put myself, I will be captain,
male from Matthews and let's click register,
okay that worked sort of, but let's go back now
and forget my name and click register.
Okay, so now we have some user feedback,
so before I was just punting, I was sending the user
on my merry way if I screwed up, but if I go into Frosh Ims 2,
notice that this version almost the same,
but it submits to Register 2.
So I am going to open up register 2.php
and in here I see oh interesting there is actually no logic
up at the top.
So to make clear the structure of PHP,
this is a good thing and a bad thing.
PHP is kind of a messy language, because you are co-mingling code
with static content and in general especially
for complex projects, this is frowned upon
because things get messy very easily,
but on the upside is it is so damn easy to do things quickly.
Right even that Twitter site, again I will harp on it,
it only took a couple of nights of playing
around to get working.
And you know, it is not the most beautiful thing underneath the
world, I could completely over engineer it with something
like Java, but my goal was just to do it and get to sleep.
So again, these are trade-offs, they are just another resource,
your own time is a factor when making design decisions.
So here notice what I have done for the first time,
inside of the body of my page,
I have actually said oh wait web server, here comes some logic,
process this before sending the output to the browser
and notice I have done this open bracket, question mark,
then I have if closed name equals, equals nothing,
so I have that same check.
So notice what I do this time,
if any of those fields are blank, notice here at the end
of the if statement, new syntactic detail.
I have a colon, because I then have a closed question mark,
closed bracket, so this means logically if the stuff
in between these two angled brackets
and question marks evaluates to true,
spit out the following stuff raw,
just sent it to the browser.
So what do I send, well I am sending
to the browser this sentence, you must provide your name,
gender and dorm, go to this URL, go back.
So I am just yelling at the user, else notice this,
I am back in PHP mode, open bracket question mark,
closed bracket here else colon, you are registered.
And just as an aside, no let's keep it simple like that.
The new syntactic detail here too is that at the end
of this block, I explicitly say end if, so PHP knows
that it is the end of this condition.
So you can drop in and out of PHP mode fairly seamlessly just
to put different contents where you want.
So that alone is useful and there is one other paradigm
that I wanted to introduce before we improve this otherwise
fairly quick and dirty frosh IMs registration.
So now this version is fundamentally different,
this is Frosh IM 4.php which you also have a print out of.
It is kind of rubs me the wrong way that I have files
like Frosh IMs one submitting to register one
and Frosh IMs 2 committing to register 2,
because what happens is that if there is a mistake, the user has
to hit back, the back button.
And the problem with this on a lot of websites is
that if you hit back and you just filled
out a really big form, but you made a mistake what happens
sometimes when you hit back.
>> You lose it.
>> You lose all of the form.
There is nothing more infuriating
than a poorly designed form,
especially when it is asking you lots of questions.
Now this really lends itself to that risk, if I click back,
unless my browser is being friendly to me I am going
to use some of the content.
Not always, it depends
on various design decisions, but that can happen.
And just plus, it would be a lot nicer in terms
of user interface, give me the feedback
on the same page the problem exists on,
don't put the burden on me.
You are the computer.
You are smart enough to know where the problem was,
show me, don't tell me.
So Frosh IMs 4 is a fundamentally different approach
in that if I scroll down to my action line here,
notice to what file it happens to submit.
It submits to itself.
So this is kind of a neat trick and it allows you to clean
up your code a little bit and consolidate into fewer files.
So now I have Frosh IMs 4.php submitting to Frosh IMs 4.php
and that is fine, but now I have
to consider there is kind of two cases here.
Someone is going to visit Frosh IMs 4.php with a browser,
either for the first time in which case,
I need to just show them the form.
There is no errors.
There is no yelling, just show them the form,
because they are here for the first time.
But case two is they are here, they have submitted,
they are back here, now I have got some input from them,
I need to tell them either yay or neigh
that they did a good job filling out this form.
So there is two cases, so that just sort of asks
for a condition at the top of the file.
So let's scroll up to the same file Frosh IMs 4 and aha,
there is in fact an if condition here,
so I am doing this little check
and there is many different ways to do this.
I tried to pick a simple one, if the value of action,
which is some parameter defined in the form is non-zero.
If it is true, if there is anything there,
do the following.
So this very simple if clause at the top
of this file is just a little check was the form submitted
or not.
If it was submitted, proceed
to execute the following lines of code.
If it was not just submitted, just go about your merry way,
dump the entire contents that are static to the webpage
and be done with it as usual.
So what am I doing if the form was submitted,
well I am doing this sanity check.
So if the name field is blank or gender is blank
or dorm is blank, interesting I am setting a new variable called
error equal to true.
So PHP supports Boolean values as well
and notice I have not declared error,
so this is a good thing and a bad thing.
I have declared error inside of curly braces no less,
but unlike C, which would have this variable error living only
within this tightly structured scope,
it would disappear elsewhere,
it turns out that the moment you declare a variable in PHP,
if it is not in the function, if it is in the file itself,
it becomes global automatically.
So that is useful, it is also a little messy,
but it is a trade off here.
So this means error is true if the user failed
to provide a name, gender or dorm, but it is just not set,
it is false if they didn't make those mistakes.
So I get an implicit value of false, so where is it useful.
Well let me scroll down to the actual content of the page,
notice that this isn't quite all raw HTML this time or X-HTML.
Notice that I very subtlety nested inside of this file,
this line here, beneath the big bold setting heading of register
for Frosh IMs, notice I have got a condition.
I dropped into PHP mode momentarily and I said if error,
if error is true, if I actually set it up top in the file,
what do I print, well what message gets printed.
You must fill out the form, how did I do this, well it turns
out there is this tag called div,
div makes a division of the page.
It is like putting an invisible rectangle on the page
that you can fill with content, style is very related
to our discussion of CSS on Monday.
This is just a quick and dirty way
of changing the style of an individual tag.
Classes and that stuff that we discussed very briefly is a way
of factoring out this, but I just wanted something quick
and dirty, so I say the following style
of this text should be red, color:red,
so let's see what happens.
This is Frosh IMS4.php and let me go in here, hit enter.
Alright, I am going to go ahead and not provide my name,
but I will say captain, mail and Matthews again and register.
So much better, so still imperfect, lots of rooms
for improvement still, but now we are finally taking baby steps
if you will to a much more realistic website
that provides you with immediate feedback.
This is not the only way that you could implement this logic.
I could have done you the checking later
in the form maybe.
I could have used different variable names.
So realize too the process of implementing P set 7
and 8 will be somewhat exploratory
and you will see different paradigms from me
and from the teaching fellows because a lot
of the stuff is fairly young too and it is a language
that is constantly evolving, PHP in particular,
so there are different approaches
to these kind of trips.
But the basic ideas all boil down to like week zero concepts,
which is kind of cool that these same things are now actually
proving useful, so the problem now is
that we are using my Gmail account for the registration
and this doesn't scale very well.
if you are running something like Model UN
and you have hundreds of registrations
and not just a handful from captains around campus,
you kind of need something better,
I mean even an Excel spreadsheet would be nice,
because then we can manipulate things, I don't have to copy
and paste, so I kind of like to have a Microsoft Excel document
that maybe has something like a column for name
and then captain, yes or no, and then gender and then dorm.
And then like row by row, all the registrants for Frosh IMS.
Well I can do a number of things here with PHP,
just as I can do generate raw text as we saw
with my quotes program, just as I can generate X-HTML
as I started too with that same example
and we have been doing here,
I could also just generate a text file that has a bunch
of fields separated by what special character.
So I could just use commas, I could write a program that just
like you guys are doing for problem set 5, you used F open
to create a new file and dump binary data to it,
you could just print textual data.
So I could create my own little database in just a CSV file
in my account and that is not bad, but it also does not scale.
Facebook was not implemented with CSV files
and most websites, even CS50's website does not use simple text
files, because you want a little more dynamism
and you want more performance.
You want more performance than simple text files allow,
so there exists these things in the world called databases.
My SQL is a popular one and it is one
that still drives much of Facebook.
Oracle is another one, Microsoft Access,
Sequel Server is another, there is a whole bunch of them.
Some of them are free, some of them are not free.
My SQL happens to be free and it happens
to be the most popular one at least
in the open source community and also just in typical websites.
So if you guys go out after 50 for your student group
or for your personal use and go buy a domain name
and host it somewhere, you will have access to my SQL.
So that is what we are going to use for CS 50,
My SQL is a relational database.
A relational database just means that all of your data is stored
in rows and columns, multiple tables.
So essentially what a relational database gives you is a fancy
version of Microsoft Excel.
Excel has as you may know this feature of worksheets
and at the bottom left here is where I am clicking so think
of an Excel document as a database,
think of worksheets as tables.
So what you will be given
for problem set 7 is your own database,
it is going to be called username_Pset7 and in
that database you can create any number of tables.
And you are going to have to create one or more tables
to implement this thing called CS 50 finance.
So let's see if we can't take a step toward that idea
by solving this Frosh IMs problem a little better.
What I essentially want to do is implement the database
that stores fields like this, well you could do this,
back in the day if you wanted to use a database,
you would type a command like My SQL
and you would specify the host, which is going
to be what do I want to say here,
let me do one little difference here.
You would do type a command, My SQL,
you would specify your username, you would specify P
for your password and then you would get a very retro black
and what aski art like interface to a database.
Kind of annoying, although My SQL stuff is very powerful,
so it is kind of underwhelming for what this thing can do.
I mean Facebook is, not to harp on that particular example,
driven largely today by My SQL databases.
So let's take a look at what this looks like.
We have a program and it is actually free,
which is why we went with it and it is very popular
and it is called PHP My Admin.
This is just something that some really nice people wrote.
It is freely available and it is a graphic interface
to managing a My SQL database.
There are many different ways to manage a database.
A database is just tables stored in memory,
but actually interfacing with them is nice
to do via graphical user interface so I am going to log
in with my mail-in user name and with my mail-in password here
and I am going to get this interface.
And you will get to know this interface a little bit
with Pset 7 and 8.
I am just going to give you some highlights today,
most of this is overwhelming and unnecessary today,
but notice at top left I have a list of databases.
I already created for myself a database
for my CS50 final project for P-set 7 and P-set 8
and then also for lecture today.
So if I click this database what I now have is a way
of controlling these tables that I need to create.
So right now, I actually have one table,
because I was practicing before class.
I am going to click very quickly this little X button and get rid
of that, so now I have a database with zero tables.
Think of this as an empty excel document,
so I need to define some structure.
So I am going to click structure, actually
and then it is going to create new table on database,
alright what do I want this new table to be called registrants.
These are the people who are registering for the sports
and I have got four fields, name, captain, gender, dorm.
So four fields, I am going to click go and now
in here I get kind of an overwhelming interface partly
because my resolution is kind of low on Sander's screen here,
but it is just asking me to tell it what these columns are going
to be called.
So in Excel, I just literally type them.
A database is a little fancier, it wants to know what the name
of the fields are, what data type is going
to go in them and so forth.
So let me just type this in, name and then captain
and then gender and then dorm,
but then these shouldn't all be integers.
So notice in this drop down,
this database called My SQL supports a whole bunch
of data types.
Some of them are strings or texts, some of them are binary,
some of them are floating points, some of them are dates
or times and what is really nice to be honest about PHP my admin,
it is kind of a learning tool onto itself.
You can kind of teach yourself a little bit
about what My SQL provides by just reading the menus
and picking what makes intuitive sense.
In this case, I am not going to use text,
I am going to use something called Bar Char.
This is a variable length string.
Now how long is a person's name supposed to be, well it feels
like maybe 100 characters max, something like that.
I am going to say 100 characters max for a typical person's name.
Captain, okay you know what, I am actually going
to make captain be a Boolean,
because it is just going to be true or false.
Gender, I am going to use something called an E num,
I only want to allow two values in this field,
so I am actually going to enumerate
with single quotes either F for female, or quote M for male.
And what this means is it is a textual field,
but it is an enumeration.
Only one of these two values is allowed
for my particular implementation here.
And then I have for dorm, dorm should probably be bar char,
dorm names, they are less than 100 characters each.
Now there are some other features
and we will discuss these over time, but I am just going
to leave the rest of this blank, so don't get distracted
by all of your choices.
I am going to click save and now what you see up here,
what is also nice about this tool is you can actually learn
what sequel syntax is by way of this program.
So SQL, structure query language is a database language.
It is not specific to My SQL, any of these popular programs,
Oracle and the like support this language called sequel, SQL,
which allows you to get data from a database
and put data in a database.
Now it is not all that interesting to learn the syntax
for creating tables and this font is kind of poor
on this screen, but notice it says create table, mail-in,
lecture registrants name, captain, what this program does
for me is it you know shows me the syntax it just used
to create this database.
It is just a front end to simplify my life.
So now I see a reminder of what I just created so all
of this information here tells me what my database my now looks
like, so my goal is to insert some values into this database.
Well let's see how I can do this, well one I could manually,
especially if I am the proctor and some student calls me
on the phone or doesn't know how to use the web,
they still are sliding this piece of paper
under my door, I can do it manually.
So I click the insert tab
and I can say okay David really doesn't know what is going on,
Captain he is going to be, no not a captain, not qualified;
male and then let's say Matthews.
So I can just do this manually and this is not the value added
of a database, because the whole point is not
to do this manually, but I can do it just to get me started,
because now what it executed is this syntax, insert.
So it turns out that SQL supports some fairly basic
instructions and the quick list is just this select to get data
and insert to add data, update to change data and delete,
so essentially four, these are the four most important
constructs from SQL, which we are going
to manipulate a database.
So what I just did in this example here using this
graphical tool, it did the syntax for me.
Insert into the mail-in lecture registrant the following fields
with the following values.
So I want to mimic this same behavior.
So what I am actually going to do now is this,
I am going to go back to my code here.
I am going to go into my public HTML directory
and my source code for today for Frosh IMs
and now I have Frosh IMs 8.php.
So let me pull this up, version 8,
aesthetically it looks pretty much the same,
but this time instead of copping out and just emailing
that proctor or myself or Jensu, we are actually going
to insert the data into this database,
because then you can imagine taking some time
and actually writing a webpage that not inserts,
but selects that same data from the database
and shows it on a webpage.
So case in point, when you actually visit CS75.net/staff.
We did not implement this webpage in X-HTML,
we wrote a PHP program that actually queries our database,
grabs all of the staff members from a staff table and loops
over them in alphabetical order
and then generates the X-HTML dynamically.
So it is the same idea, because again I don't want to have
to maintain X-HTML for 60 different people,
much easier to put in a database
and dynamically generate it as you see fit.
Alright, so here is my Frosh IMs 8 and notice the only difference
for this front end is that I am submitting to register 8.php.
Alright, so I am going to go ahead and open register 8.php
and here is what I am going to do.
First a sanity check, if the user failed to give me a name
or gender or dorm, forget it, reject them, send them back
to Frosh IMs, slight typo, don't look yet.
Send them back to FroshIMs 8.php, but if they don't screw
up and you don't exit, continue executing,
so it just takes a few lines of code here.
So let's see the first line of code
and I have just revealed my personal password My SQL
connect, how do I want to connect
to the database using PHP, well I want to connect
to what is called local hosts.
So when you want to connect to a database on your own server,
you generally call it local host, but you would be told this
by the system administrators or in our case the course,
then this function expects a username,
then this function expects a password and then semicolon.
That opens a network connection to the database,
but then there is going to be 300 plus databases living
on this server, in fact, 900 databases, because you are going
to get one for P-Set 7 and 8 and final projects if you want it.
So I need to select using this function,
my SQL select DB mail-in lecture, so this is going
to say connect to the database and use this lecture
and because I provided a username and password,
I am only going to be allowed to call this line of code
if mail-in actually has access to that particular database.
So this is just authorizing me for access.
Now how did I know any of this stuff, well in fact,
one of the best things about PHP, so it has some downsides
and it is potentially a messy language
and actually let's do this my SQL connect,
so PHP.net will become a friend over the course of PSet 7 and 8,
because frankly of all the languages we will play with,
it is by far the best documented.
You can literally learn most of the language just
by RTFming what is on this website.
I mean to be honest and it is no overstatement after learning C
and C++ and Pearl on my own, I personally literally learned PHP
by IM-ing a friend over AOL Instant messenger back
and forth, just peppering him with questions,
like he blocked me after that.
But that is literally testament to the relative ease
with which you can kind of pick up some of these new things.
Alright, Google is now my friend, instead of my friend.
[ Laughter ]
But it is relatively easy to bootstrap yourself
so realize it is very much deliberate
that you know we wave our hands at some of the details,
so I went to PHP.net, I typed My SQL connect into the search box
and walla I now have the documentation for this function.
Now it doesn't matter so much all of the details here,
but what is really nice about the documentation,
because those man pages, as much as we preach them, they are kind
of arcane right, sometimes it just makes the problem worse
when reading the documentation
because they are not always that clear.
PHP.net is nice, because it always comes with examples.
So down here, we see the name of the function,
this is admittedly a little cryptic, so we will come back
to that and we will see easier functions over time,
but I am going to scroll down here and now here are examples.
My God, this is all I want to do, if I want to connect
to a database, I call My SQL connect, I pass in this
and my username and my password
and then there are some other techniques here too.
So constantly refer to the PHP documentation if
and when you have questions over the course of those P Sets.
So here is the code, I have connected to the database,
I have selected my own, how do I now insert the data the users
provided me with.
Well the goal is to get the contents of that post variable
into the database, well let's see.
I am going to declare four variables, name,
which is right here, captain which is here or here,
depending on the if condition, gender and dorm.
Now what is with some of the crazy syntax here.
Well name is simply going to be the value that the user gave me,
but users can be obnoxious and they can try
to break into your web server.
They can try to break into your computer
by providing bogus input and we have discussed this before,
really a problem on the web, because it is so easy
to pass inputs to people's programs
when you just have a browser.
So this admittedly stupid long name function,
My Sequeal real escape string is the function to call
for any time you use this library
to access My Sequel databases.
This makes the user's input safe.
If they put some crazy syntax in there that is designed
to break your database or steal your data,
this function My Sequel real escape string makes
that not a problem, so just as a teaser and we will talk
about this at some point if a user got malicious
and didn't type in David as their name,
but delete as their name, the point is you don't want
to pass the word delete to something
like a database lest it actually delete your data.
And this happens all the time, because people fail
to massage their data with functions like that
or to scrub their data so to speak, alright.
So this just puts the name,
but it escapes it using a very safe mechanism.
Now captain is actually going to come in as like an on/off value,
it is going to come in as a string, so I am just going
to check if captain is non-zero, so if the person checked
that box, declare a variable called captain
and make it a bool, make it a 1.
I could have said true, but actually I intentionally said 1
so that My Sequel gets a 1 or if they didn't check that box,
assign this variable as zero.
As you know gender, same thing as name,
escape very safely whatever they checked for gender and for dorm,
escape whatever they typed in for dorm and now the only line
of code I need to execute here is this,
I am going to declare a variable called SQL,
this is me being anal, I like to create my string in a variable
and then do something with it.
So SQL gets the following value: insert into name of the table
in parentheses I now specify a common separated list
of the fields I want to insert, pretty easy,
it could be any order.
I chose this one and then it is wrapping,
so let me just hit enter once to clean this up a little bit.
Then I type in the word values and then notice,
closed parentheses here, open parentheses here
and then now notice, I am using single quotes to quote each
of the strings name, gender and dorm,
because captain is a bool, I just pass it in.
So in the end, I have a string that reads insert
into registrants, name, captain, gender, dorm,
values David, zero, M, Matthew.
And that is sequel that is the language called Sequel
that I just so happen to have embedded in a program
in another language called PHP.
So now if I want to tell PHP execute this instruction
on the database to which I have a connection,
I simply call My Sequel query passing in this string, wa la.
That should do the insert automatically
that I previously simulated by clicking some buttons.
So let's give this a try, so right now if I click browse,
I see that okay I just have one user, zero David M Matthews
and I did that manually.
So let's go to the actual web form here,
let me go to Frosh IMs 8, alright so I am going to type
in now Jensu, Captain, Female and I don't remember,
say Apley Court, register.
Alright, you are registered really, now let's go back
to my database and this is just a tool.
I want to see what is in my database.
I am going to go ahead and click browse again and wa la,
Jensu has been inserted into the database.
Now very simple, we haven't really solved a big problem
here, but now assume this is now Model UN
or some student group's problems,
now you can have hundreds of people going
to a relatively simple web form clicking submit
and now you have a table of information,
but what can I now do with that information.
Well let me do this, let me make a quick and dirty file, a quick
and dirty program, which is just geek speak
for saying let's do this fast
and not necessarily the best way.
Let me copy register.8.PHP, call it registrants.PHP,
I am going to open registrants.php.
Let me get rid of my comments at the top,
I don't need to validate anything.
I do want to connect to the database again, I don't need
to scrub input, I am not going to take any input from the user
and this time the query I am going to execute is this.
I am going to say select star from registrants and that is it.
So this sequel instruction is actually going
to select information from the database.
Let me scroll down here and I am now going
to say let's see I have execute the query, but this time I need
to care about the result, because I want information back.
I am not just putting it in, so I am going
to say results gets my sequel curious return value
and now I am going to say iterate over results.
So while row gets, it is called My Sequel Assoc,
Associative Array, result.
So this line of code is just going
to ask iteratively give me a row, give me a row
and each time it is going to put it in dollar sign row
and so what do I want to do with this information.
Oh interesting, I don't really want to put it up top
of my webpage, so let me scroll down here, let me butcher most
of my code here and what I am actually going
to do is steal this, one, two, three, four, five lines of code.
I am going to move them to the bottom of my file.
I am going to jump into PHP mode here.
I will intent just to keep things a little pretty
and now I am going to close PHP mode.
So what I am going to do here is simply print out,
see I want to print out for the first person,
row and what is the person's name, so it is name.
I want to print out the field called name, alright now I want
to print out, okay this is X-HTML.
Let's print out a line break explicitly, so not back slash N,
this is a webpage now, BR.
And now that is enough, I just want to print their names.
So let me click save, now this is registrants.php.
Let me go to my file here
and type registrants.php enter, wa la.
Now I have an administrative interface,
where the student group leaders can actually see
who is registered for this particular thing.
So where are we going with this well in problem set 7,
you are going to be handed a bit of a framework.
So we are going to give you some code to simplify some things
that it is not worth getting hung over initially,
so we will get you started with this.
So we are going to implement a few different features,
so one we are going to hand you a log in mechanism
so that users can actually log into your website.
But unfortunately we are not going to hand you ability
to create accounts, so initially you will have to go to something
like PHP My admin and the pdf will tell you how
to access your account,
what your default password is and all of that.
So you will use the insert tab initially
to create a fake username and some passwords for yourself,
so that you can actually start logging
in to this CS50 finance site, but that is not very interesting
because then are you going to add the feature not just
to register accounts by the web, but to get stock quotes
so you are going to have a webpage called quotes1.php,
something like that.
You are going to have a little form asking
for a stock symbol and a submit button.
The user is going to type in Goog enter.
That form is going to submit to another PHP file and what is
that PHP file going to do besides the scenes probably,
it is going to contact who for the data?
So literally Yahoo finance and we saw
and I will make this code available the little four lines
of code, five lines of code to talk to Yahoo,
get back the current stock price from Google, put it in an array.
You can then certainly print that to the screen very easily
so that is not so bad, then it gets a little more interesting.
You are going to have to create the ability to buy
and sell these stocks.
So by default, each of your users should get something
like 10,000 dollars in virtual dollars in their database.
So rather than just have fields like name and dorm
in this database, we will actually have another field
in there called cash, how much cash does the user have
by default and you will probably in fact have another table.
So even though we just used one table for Frosh IMs,
you probably want a table that is going to keep track not just
of your users, but a separate table,
a separate Excel spreadsheet if you will that keeps track
of the portfolios of your users,
what stock symbols have they bought and at what price
so you know what their net worth is.
And then finally, you will need to keep track of this history
so you know what the user has actually done and just
as we will finish problem set 5 and the so called big board,
we will replace this big board with another,
we will actually debut a little stock trading program,
which is so much fun when the stock market is
in the condition it is.
Oh that is cute, you are the only one in this room
with access to that account.
[ Laughter ]
That is beautiful.
Why don't we just end on that note, see you Monday.