Blog 12

Today we continued learning about implementing a competition database with our website.

Class notes:

To continue the work we were doing last week to create a competition database here is the sql for making the database:

CREATE TABLE Competition (CompID INT AUTO_INCREMENT PRIMARY KEY,CompName VARCHAR(255), compdesc VARCHAR(255) StartDate DATETIME, EndDate DATETIME);
CREATE TABLE Question (QuestionID INT PK AI, CompID INT FK, QuestionText TEXT);
CREATE TABLE Proposed Answer (AnswerIDF INT PK AI, QuestionID INT FK NOT NULL, AnswerText TEXT, IsCorrect INT(1) NOT NULL DEFAULT(0));
CREATE TABLE Competitor(CompetitorID INT PK AI, Classroom VARCHAR(255) NOT NULL. Email VARCHAR (255), SchoolID INT FK);
CREATE TABLE School (SchoolID INT PK AI, SchoolName VARCHAR(255) NOT NULL, SchoolPhone VARCHAR(25) NOT NULL);
CREATE TABLE Competition_Responce (CompID INT FK PK, AnswerID INT FK PK, COmpetitorID INT FK, WHEN DATETIME DEFAULT non());

The phpmyadmin GUI database editor was not the easiest to use, particularly in the process of setting foreign key constraints. I tried setting the foreign keys with the relation view after making the tables and it was unreliable if it actually worked.

So in class I wrote up SQL code so I can set up a file that recreates the database quickly if I need to drop and then recreated the database in the future, rather than using a GUI editor.

Our competition form needs to have the following:

  • Classroom
  • Email
  • School
  • SchoolNumber
  • Competition Question
  • Proposed answers

 

There will be INSERT queries into the following table fields:

Competition

  • CompID- From form

Competitor

  • Classroom
  • Email

School

  • Name
  • Number

Response

  • CompID
  • CompetitorID
  • AnswerID-From form
  • When (when submitted this information is from the form)

Question

  • QuestionID- From form

On the form will be hidden the AnswerID for each of the proposed answers and the QuestionID for the displayed question, this is so the questions and answers can be identified

CompetitionID hard coded (piece of code containing CompetitionID in the php code) into the view because we don’t know what the competition is.

When form submitted the form is submitted to the controller, and this is sent to the database object to be inserted into the database.

The process for inserting into the database after submitting the form is:

  1. INSERT School

INSERT INTO School(SchoolName, SchoolPhone) VALUES ($_REQUEST[‘school’],$_REQUEST[‘SchoolNumber’]);

This will create a string, inside SQL we have to use single quote for a schoolname which is a string. ‘”. this concatenates the school. You start a new string with a single quote character.

Model runs the INSERT INTO School. Create a database object and run this query against it.

$SQL=”INSERT INTO School (SchoolName, SchoolPhone) VALUES (‘”.$_REQUEST[‘school’].”‘, ‘”.$_REQUEST[‘SchoolNumber’].”‘)”

Todd recommended making a model class named Insert for School.

 

Making a form: Below is a basic form

<form method=”post”  action=”form_controller.php” onsubmit=”Return true”> //Onsubmit will contain JavaScript for making validating the form before submitting it

Classroom <input type=”text”  value=” ” name=”classroom”>

School <input type=”text” value=” ” name=”SchoolName”>

<input type=”submit” value=”win!” name=”Command”> //Controller will look for a command named win!

</form>

NOTE: In order to submit information to server you must give input type a name, the value of the name is what you put in the request.So in model you would write $name=$_REQUEST[‘classroom’]; The classroom name will contain the value that the user wrote into the input field, and this line will store this inputted value into the $name variable.

Use the POST method for forms as it hides the contents of the form from the user.

 

In your website you will have the following folders:

/views

/controllers

/models

With new model class (which can be a new model file) for the form model. Similarly you can still use fat controller method where you have one controller for the whole website (i.e. the controller deals with the website and the form handling) or you can make a new controller file which just does the handling for the form and decides what query in the model to run).

The SQL query is stored in the model.

Project Notes:  I need to start building the form for my website, and will start creating a controller for the form.

Blog 11

Class notes

Today we looked at designing the conceptual, logical and physical database design models for the database used for the competition feature of the website.

We started thinking about the competition feature of our website; which is a competition form accessible from the home page of the website. The competition form has a random question displayed which a set of proposed answers.

Looking at the competition (which will retrieve data from and submit data to a database), we looked at the information that will be required in the database for this competition. Our database needs to store information about the following entities (which will become tables in the logical model):

Note: underlined is a candidate key to identify a record uniquely

  • Questions- (Question (this is the question text as each question is unique it is the candidate key))
  • Selected Answer (responses from the competitors)- (DateTime)
  • Answers (set of proposed answers for a given question)- (Answer text, is correct)
  • Competitors- (email, classroom)
  • Schools- (School, School Telephone) composite candidate key
  • Competition- (unique name of competition, start date, end date, description)

There was a discussion on the ethics of storing the competitors email address. Todd believed storing the students email address was unethical, however in a discussion with the class it was suggested to use a school email address. The problem with this is how do you keep track of how many competition submissions have their been for each school to stop cheating. In the end we allowed the use of student emails to be entered to the competition form.

The competition form will ask:

Classroom:

School:(If you write in an existing school name then nothing is updated in school entity, but if a new school is added then the school table is updated. But in the next milestone (milestone 3) we need to implement the functionality an active search as user writing in school name then goes off to the server and the server provides a mini view displaying a matching school name predicting what you want to write in (You can either add to the school list as you go, or use government school list.))

Student email:

School telephone:

Competition question:

Proposed answers 1) 2) 3)

 

After determining the information that needs to be stored, we looked how this information will be stored, so now Todd started drawing a ER diagram using Chen Notation.

Cardinality sentences of the database:

A Competition presents many  questions.

For each question there are many answers (which are true and false)

A competitor makes many responses

A competitor exists in one school

A competition has many competitors

A competitor competes in one competition (as only one competition at a time)

A school has many competitors

A proposed can be a selected answer many times

For every selected answer there is only one proposed answer

There is an identifying relationship between Competition, competitor and selected answer.

Conceptual model:

conceptual.JPG

 

Logical model:

Note: The question table will have the QuestionID primary key because it is easier than using a question text string as the primary key.

Similarly the Competition table will have a CompetitionID primary key, as Todd wanted to use a numeric primary key for the Competition table.

Similarly the Proposed Answer table will have a AnswerID primary key, as Todd wanted to use a numeric primary key for the Proposed Answer table.

Competitor table now has the numeric primary key CompetitorID.

School table has the primary key SchoolID.

logical model.JPG

 

Project notes

I need to start making a database for my website by using PhpMyAdmin to make a database named CompetitionDatabase which will have 5 tables based on the logical design made in class.

Blog 10

Class Notes:

Today we looked at Milestone 2 which connects to a MySQL database using PHP website.

Milestone is moving from the initial analysis to more detail about our  project. We will extend and develop the website, we will add the extra characteristic of a competition page accessible from the home page.

This competition page will be a form which the user has to fill out for schools to win a computer. This competition page will be accessible from the home page via a graphic link.

This competition page will have fields to be filled out and competition question with radio-buttons answers. The competition page will have data retrieved (from DB) and data submitted to DB.

The competition question will be about the website so they have to go through the website.

Before the data is submitted a question must be retrieved from the database to be displayed on the form.

Because when the form is first displayed the question (is a random question from a database set of questions, i.e. competition is generated and extracted from the DB), and this will be displayed on the form view which makes the competition page a active view.

The database will have 5 tables in a relational database.

After filling in the competition form then there will be a thank you message which will be displayed (this thank you message will be coming from the database).

We will build a controller (dealing with form, can be same existing fat controller, or a second controller), model and view (the form is treated as a view).

Milestone 2 will have a new chapter in the IA report describing how you are building the website. Cite code from other sources.

This is the php code we used to connect to a ‘food’ database we created using phpmyadmin:

<?php
    
    class DBconnection {
        private $rs; // Procedural "handle" or "resource" to database
        private $connectRs;
        
        private function connectDb($pStrDatabase)
        {
            $this->connectRs = mysql_connect("localhost","root","");
            if(!$this->connectRs)
            {
                echo "Error connecting to the database server".mysql_error($this->connectRs);
                $this->connectRs = -1;
            }
            else
                echo "Connected </br>";
            $dbRs = mysql_select_db($pStrDatabase,$this->connectRs);
            if(! $dbRs)
            {
                echo "Error selecting the database".mysql_error($this->connectRs);
                
            }
            else
                echo "Selected ".$pStrDatabase."</br>";
        }
    
        public function query($pStrSQL)
        {
        
            $this->rs = -1;// BAD RECORDSET
        
            $this->rs = mysql_query($pStrSQL,$this->connectRs);
            if( !$this->rs)
            {
                echo "Error running query [$pStrSQL] ".mysql_error($this->connectRs)."<br>";
                $this->rs = -1;
            
            }
        
        
        }
    
        public function DBConnection($pStrDatabase)
        {
            
            $this->connectDb($pStrDatabase);
            
        }
        
        public function next(){
            $aRow = mysql_fetch_assoc($this->rs);
            return $aRow;
        }
        
        public function free(){
            mysql_free_result($this->rs);
        }
    }// end of database class
   
    // Test Code using Food database
    $aDB = new DBConnection("Food");
    $aDB->query("INSERT INTO `Ingredient` (`Name`, `Description`) VALUES ('GARLIC', 'Smelly')");
    $aDB->query("SELECT * FROM INGREDIENT");
    
    while($aRow = $aDB->next()){
        echo $aRow['Name']."  ".$aRow['Description']."</br>";
    }
    $aDB->free();
    $aDB->query("DELETE FROM INGREDIENT WHERE `Name` = 'GARLIC'");
    
    
    
?>

I went through and commented this code. But when I ran the code it threw an error because i have php version 7 which considers mysql deprecated and uses mysqli (which is OO version of mysql) so I had to write i at end of mysql in the above code and change the query parameter order around so the connection was first followed by the query,, then after I ran the code it worked successfully.

 

Project Notes:

I will start working on milestone two.

Blog 9

Today in class we each went up to see Todd and showed him our work. When I went up he was happy with my project however I needed to make the following changes:

  • Introduction about the website
  • Summary of the competitive analysis
  • Summary of the scenario
  • And to remove the discussion of link to other pages from the local navigation.

I made all these changes and I also indented my code so it was nice and today, I also commented my code with big paragraphs about the model and control_Class.php file.

Then I had to spend a lot of time shrinking the size of my report so it could fit in the assignment Dropbox which had a maximum size of 20Mb.

After that I submitted my milestone one, I am happy that I have got that submitted and ready to move onto the milestone two.

Blog 8

Today Todd went around and caught up with everyone, I found this to be very helpful because I had been working on trying to get my model working since 6am this morning without success.

Todd suggested the method of implementing the MVC (Model View Controller) pattern by having the model and view being instantiated in the controller rather than at the bottom of the view.

He also suggested creating a function inside the case statement for each of the navbar links such as case “Home” had the function GetHome(); and inside the GetHome(); function you instantiate the model (of the name $thisModel) and the HomeView (of the name ($HomeView) and then render the model inside that $HomeView:

$theHomeView->Render($theModel);

This allows the model for the HomeView view to be rendered and can be sent from the model to the view to be displayed by the browser.

I hand the Render function the parameter $thisModel which is the ephermeral model object (created for each of the pages in the navbar). I want the Render function to use the $theModel object.

Then at the bottom of the control_Class but outside of the Controller class I create a instantiate the Controller class and name the new instance of the Controller class $thisController.

I then call the accept(); method inside the $thisController object. This is the vital function call that ensures allows navigation between the pages of the website through the switch statement checking which button the user clicked on.

 

To do:

I now need to indent, and comment my code and then improve the naming conventions. Then go back to my I.A. report and describe why I did what I did in the wireframes. Then I should have completed milestone one for WEB601.

 

 

Blog 7

Assignment milestone 1 notes:

We need to make sure that the goals are the reasons for why we are building a website rather than a list of tasks to build the website. We need to have a list of goals

e.g:

Get student to visit the site

Get student to complete the cooking tutorials

Use the website as a information sharing environment.

 

Class notes:

Todd showed us the fixed version of the PHP code.

A session is a defined usage of the system in a contiguous period of time. With session management systems the session is determined since your web browser has last closed. Session management systems use cookies and they are closely related, and so it depends how it has been set up. In a session management system there is usually an identifier associated with the system. The identifier will store information related to a session.

What PHP does is it uses a database with information on all the sessions, so you can replace the session management with my own code. But in Todd’s code he is using a static storage array.

You can have a controller attached to every function in your code. In the controller we have:

The PageView is instantiating (creating a copy of itself).

 

If I had a e-commerce website the shopping cart items would be stored in the database, and the session would have to store that it is the same computer accessing the website. The session variable (issued from DB, if it isn’t set you do a request for a new shopping cart id) has the shopping cart id stored in it, the shopping cart id shows that it is the same computer.

The model is rebuilding itself all the time, and it is using the session to get information from the session.

So the persistent data is stored in session variable and database system. Note: Before using a session variable you need to make sure it is set first.

 

The other option is to dump the model as a object into the session and retrieve it every time. So it can be retrieved between sessions but this is unreliable as you have to serialize the model. But this is not ideal.

We made changes to Todd’s code.

Project work:

I have fixed up my site goals so they are goals for the website as opposed to tasks required to build the website.

The milestone 1 is due next Thursday. We need to use PHP using MVC model to build the website. But we are not required to have the appearance of the website finished.

Blog 6

Class notes:

Today it was a continuation of Wednesdays work on the PHP scripting notation. Todd came and had a look at our projects progress, and then came and saw that we could connect to the Bigears2.com web host.

PHP control structures-

  • foreach is an interesting control structure it lets you go through an array (An array-expression is a associated array of arbitrary indexes, an array is a store and each value has a index value which you use to search the array) and pull each data value out of it. foreach is used to pull a result from a datastore often.

In PHP you can have name as index and information storing about the person as the array.

e.g. you may use a foreach to pull the results of a database query.

$key=>$value this expression lets us declare a name value data.

  • Break is used in a switch statement it
  • Switch- This is a specialized or branching situation.
  • Return- This should only be used at the end of the function as function has one entry point and one exit point.
  • Require- This will give you compile errors. Using the MVC (which is what we are doing) we should use REQUIRE_ONCE (you get one instance of the code; this control structure brings in a piece of code and runs the code which can only be used once of the code cannot run then a compiler error will be thrown).
  • Include- It includes script where it is put (it dumps the code into the place where include is written).

Dynamic web applications sometimes cross between the 2 sides (client and server).

The reason you impose an architecture (way or organizing the development of the app).

Client side

To clarify: The view displays something in the system

Model is where that something happens.  Asking for the next page is that a job for the model or the controller. Anything you want  to do to manipulate state including the state itself is stored in the model. Stores data about state of the system. Data needing to be stored by the system goes to the model.

Controller doesn’t know what the next page is. Is controlling.

 

 

Agent- (something that uses web services. e.g. Web browsers and similar)

 view -PHP (in PHP the view has markup (HTML) in it. A PHP file is a extended file that has HTML in it). The view comes from something generated on server side (if working in company you will have people experts in graphic design making html and this gets integrated with the server side).

How do you get a view- You should have 1 home view (by having a single controller which is asked (requested) to do something (process a request) and it goes to displaying the default home view.

The client side has a whole lot of technology used like jQuery, JavaScript library, Cascading Style Sheet. All these things are like a wave, constantly changing and renewing.

server side

Controller– We have many views and 1 controller, it is the application control loop.There is a request to controller and the controller sends a view back.

You could build a website with 5 views (one for each page) however if all pages have the same layout we have the potential for a dynamic website (same layout but the content changes depending what page is requested). So where does the information for each page be kept, you have a database that stores the information for different pages.

So the controller goes to database and asks for the next page:

SELECT pagex FROM DATABASE;

Then page content given to view and view has to draw it. The problem with all these queries and connections can be quite hard to keep track of. So to fix this we can ask a request from the controller with parameters and then the view that is returned hands back the

Or you can create a database object (Contains the database queries in it) and this database object encapsulates all database queries and manages them, and encapsulates the all of them very connection to the database. But the database object’s job .

The term model represents the state of the system, so everything that retains the state of the system is stored in the model. The model potentially will have to deal with session. So the model will look for information stored previously, current page, how do we go to the next page, what is in the next page. So instead of controller going straight to database, the model will go to the database to go to the next page (store what is the current page), and model data sent to controller and the view is built and send to the view to be displayed.

 

There is two pathways:

Controller-> Model “Next page please”

Model->view

There are two ways of implementing MVC:

Implementation 1 (this is the method we will use)

1 controller

1 model

 

or

Implementation 2

many controller (one for each action in the website)

many models (one for each action needing state recorded).
Todd felt we could have a passive view (graphics and interaction but it just displays what is given to it), or active view(it has the responsibility of the view asking the model for new view to display if no action is associated with the update e.g. website showing temp changes the view (it will also process certain types of requests from the client agent(web browser)) so the client asks (in HTTP request object asking for something) every few seconds tell me the temperature.

The Model-View-Controller is the most commonly used architecture used in web apps today.

 

Code:

The link in our navigator goes back to our controller control_Class.

PageView sets the model and the pageView gets the next one.

Page view is grabbing a model, the model is instantiated when it is asked for. Then I have a class based on the model (next page content) and then

 

Project notes: I just need to finish off my page mockups, and then go through and edit my report.

Blog 5

Today we looked at how to do models in PHP, and looked at the PHP scripting notation.

Class notes:

Before PHP there was ASP.NET, JavaScript, and Tomcat(servlet-little programs managed on server that run on client as well). PHP is designed for writing web pages with scripts on server. PHP is procedural programming language (it has commands to do something, has ability to repeat things, and has procedures you can write).

PHP is a web server sside scripting system which expresses OO programming, using most of the features of OO programming. PHP is also dynamically typed (i.e. the variables take the type of the data value assigned to them).

PHP tags:

<?php (this means this is a webpage with PHP in it). We must have the .php extension so the web server knows it is a web script.

All of the code in between the opening and closing PHP tags are interpreted.

?> (Closing tag of PHP)

You can write a PHP script without closing the PHP tag however it is not a good idea to not close the PHP tag.

If you want to do something on a server you just writye the opening and closing PHP tags. e.g.

<p>This is going to be ignored by PHP and displayed by the browser.</p>
<?php echo 'While this is going to be parsed.'; ?> (This script is interpreted by web server)
<p>This will also be ignored by PHP and displayed by the browser.</p>

PHP uses If statements

<?php if ($expression == true): ?>
  This will show if the expression is true.
<?php else: ?>
  Otherwise this will show.
<?php endif; ?>

All of the bolded lines of code are PHP, which can be read by web server as a single if statement. While the italic lines are conditions of the PHP if statement even though they are outside the PHP tags.

A if statement like this could be used to check if the user has logged in then do something.

There are 2 styles of notation for PHP you can use : (colon) or curly braces {} but you must not mix the notation styles.

PHP is very pedantic about semi-colons. Therefore good practice is always write ; at the end of each instruction.

PHP comments are /* or // Don’t nest your comments. Each company will have a standard for commenting and style which you must abide with.

There are only 6 types of values in PHP:

  1. Boolean-You can write upper or lower case true or false. If variablea==variableb (this is a comparer comparing using boolean if the variables are equal)
  2. Integer-You can express your number as hex or binary number, or base 10 numbers.
  3. Floating point number-Use this with parts of things. There are no fractions in PHP, but can express with divide. e.g. 1.2e3 (number to the power of 3).
  4. String-Strings are characters. Single quoted string is a string is a string literal ‘this is a string’. Double quoted string “”. Heredoc’s and Nowdoc’s are great bodies of text going into variables as strings.
  5. Array-Array is a large store of the same type of things, you can look up using a index. In PHP array is a associative array. It has a index and a value that will appear. You can use numbers or letters as the key which you can then search. In our version of PHP you use [] to define arrays. In PHP you have a name value indicator name=>value. e.g. "foo" => "bar",
  6. Object- Objects are a composite data type. Objects have methods and they have storage, so they can do things and store things. You can also have a object based on another object (this is a=called extend).

 

<?php
class foo (To make a object)
{
function do_foo()
{
echo "Doing foo.";
}
}

$bar = new foo;(create a object of foo)
$bar->do_foo(); (Make foo do something)
?>

And a special type:

  1. Resource- If you connect to a service (like a file (the file has ResourceID) which is used by the system to then connect to the file).
All variables in PHP start with a $  There is a special variable $this which uses the current object. Variables are case sensitive.
You cant have a variable name starting with number after a $.
Variables are assigned values.
Predefined variables:

Supergobal variables

$_GET- HTTP GET variable

$_POST- HTTP POST variable.

$_SESSION- Store information between pages, this uses a associative array.

If you declare a variable outside a function then try using the variable inside the function it will make a new variable with the same name inside the function. To prevent this you must write:

global $VariableA, $VariableB (inside the function)

Constants- You use the word define to create a constant.

  • $a++ this means value of $a +1
  • $g += 10; This does add g to 1o
  • To  put 2 strings together use a dot.

 

For Loop(repat for a certain number of times).

for ($a=2, $b=4; (initialize information) $a<3; (condition if not true then run the loop i.e. run the code between the curly braces)$a++ (add 1 to $a)

{

echo $a. “\n”

}

 

Operator precedence: Clone new (has highest precedence therefore run first), or has lowest precedence.

Comparison operators: To compare 2 storage areas you have to use two =

e.g.

$a==$b  (check if a is equal to b after type juggling)

Error control operator- @ in front of something will stop error messages being produced.

Logical operators- The main purpose of logical operators is to get a true or false.

e.g. $a and $b (true if a and b are true) if $a is false then PHP won’t check if $b is true (this is called short circuit).

Array operators-If you plus 2 arrays it will combine both arrays e.g. $a + $b (this is called union)

Control structures: elseif

<?php
if ($a > $b) {
echo "a is bigger than b";
} elseif ($a == $b) {
echo "a is equal to b";
} else {
echo "a is smaller than b";
}
?>

This is the correct notation..

 

While loop- Precondition loop check if something is true before executing the loop.

foreach:

<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) { (pull each value in array out and multiply it by 2)
$value = $value * 2;
}
// $arr is now array(2, 4, 6, 8)
unset($value); // break the reference with the last element
?>

(visit each item in the array and variable ($value) that will receive each item in array one item at a time.

foreach ($arr as $key => $value) { (pull out each name and value in array and print
// $arr[3] will be updated with each value from $arr...
echo "{$key} => {$value} ";
print_r($arr);
}

Grab each key and value in the array so the $value has the key (name) and value.

 

Project notes:

Finish off my HTML page mockups and edit my Information Architecture document.