Lab 8

Lab 8

PHP & MySQL II

Building a basic trivial question application


Part 1: Connecting to the database and making another table

  1. Our trivia application will constantly need to connect to the database to run queries, so we should create a function in a separate file, so we do not have to duplicate the connection code throughout our application
  2. Open Notepad++ and create a new file called functions.php and be sure it is saved in your lab8 folder.
  3. Add the following code:
    function db_connect() {
      return new mysqli("localhost", "sienasel_sbxusr", "Sandbox@)!&", "sienasel_sandbox");
    }			
    
  4. Note that this connects to the local database server and grants us full access to a database called sienasel_sandbox
  5. If you were the root administrator, you could save functions.php in a secure parent folder "outside" of the servers's public folder. But sadly, you do not have the necessary access to do this. But, at least the password is only stored in this one place.
  6. To call your db_connect function to run any SQL query, you need to include functions.php and make the following function calls:
    require_once("functions.php");
    
    $mysqli = db_connect();			
    $sql = "This is an SQL Query";
    $result = $mysqli->query($sql);
    
    // Use the result
    
    $result->close();
    $mysqli->close();
    
  7. require_once is function that "includes" the functions.php file, but ensures that it is only include once. If the file cannot be found, execution is terminated.
  8. Note that the SQL query is always a string encapsulated with double quotes. This is because SQL uses single quotes for values with spaces.
  9. Using you code from the previous lab and this new connection technique, write a new script called make_questions_table.php that creates a table for storing trivia questions.
  10. Make sure you use a URL key to protect this script so that others cannot execute it.
  11. Here is the query for creating your questions table. Please read the important info below.
    CREATE TABLE Questions????? ( 
    	id INT NOT NULL AUTO_INCREMENT,
    	question VARCHAR(1024) NOT NULL,
    	choice1 VARCHAR(1024) NOT NULL,
    	choice2 VARCHAR(1024) NOT NULL,
    	choice3 VARCHAR(1024) NOT NULL,
    	choice4 VARCHAR(1024) NOT NULL,
    	answer INT NOT NULL, 
    	PRIMARY KEY (`id`) 
    )
    
  12. Important Info:
    • Replace ????? with a five digit number, so that your table will have a unique name. Do not pick 12345 or 54321 because everyone will do this.
    • Do not use spaces in a table name.
    • Each question has 6 fields: The question text, option1, option2, option3, option4 and the correct answer.
    • The question and the four options are strings, which in SQL are called VARCHAR:
      question VARCHAR(1024) NOT NULL,
      choice1 VARCHAR(1024) NOT NULL,
      choice2 VARCHAR(1024) NOT NULL,
      choice3 VARCHAR(1024) NOT NULL,
      choice4 VARCHAR(1024) NOT NULL
      				
    • NOT NULL enforces that the question, choices and answer must have values, otherwise an insertion will fail
    • The value 1024 indicates that these strings can be at most 1024 characters long. We want to prevent the database from storing excessively large strings. An insertion will fail if our strings are too long.
    • VARCHAR can be a maximum of 65,535 characters. LONGTEXT allows for millions of characters and BLOB allows for billions
    • The answer will be encoded as an INT indicating which of the four choices is the correct answer. Thus, we do not have to duplicate the text of the correct choice in the database. We can write a query to select question, choice1, ..., choice4 and store it in an array where index 0 will be the question and indices 1,2,3 and 4 will be the choices. Thus, the answer's values of 1,2,3 and 4 will map directly to the array indices of the choices in our application.
    • Typically, it is a good practice for a table to have a the primary key, which can be used to uniquely identify questions that might have identical text, choices and answer. Primary keys are typically INT values that are auto incremented. The first inserted item will have an id of 1. Each time we insert a new row into the table, we increment the previous id by one and use this value as the new id. Thus, the primary key also indicates the insertion order.
  13. Save make_questions_table.php
  14. Use WinSCP to connect to the server and upload your lab folder to the server
  15. Type the following URL into your browser:
    http://s123456.sienasellbacks.com/lab8/make_questions_table.php?key=XXX
    where "s123456" is your userid and XXX is the secret code you used to protect the script.
  16. This will create the table on the server. We will verify that it worked soon.
  17. Notice how we use the URL parameters and the $_GET variable to prevent others from running this code. You must know the key for the script to run.

Part 2: Adding Questions

  1. For now, we are going to let anyone add questions. So, we will create a completely unprotected recursive script that generates a submission form and processes the submission form.
  2. In Notepad++, create a file called insert_question.php and add the following HTML template that includes links so you can use Bootstrap 4. We will eventually use Bootstrap's classes to make the application "mobile first".
    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <title>Add Question</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" >
      </head>
      <body>
        <script src="https://code.jquery.com/jquery-3.1.1.slim.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js"></script>
      </body>
    </html>
    
  3. In the body tag and above the script tags, add HTML code to create a form with five input text fields, radio buttons to indicate which field is the correct answer and a submit button.
  4. Your finished form should look like this:
    screenshot
  5. Be sure to include the form tag and set the following attributes:
    method="get" and action="insert_question.php"
  6. Be sure to give each form element a name, i.e., name="answer" and name="choice1"
  7. The name of the submit button should be "action" and the value should be "Insert" i.e, name="action" and value="Insert"
  8. The four radio buttons should all have the same name, i.e., name="answer" but different values, i.e., value="1" and value="2"
  9. Google how to increase the size of input text boxes so that longer sentences can be more easily entered.
  10. Add a block of PHP code to the top of the document to process the form
  11. Use the $_POST variable to save all the form values to PHP variables:
    $q = $_POST['question'];
    $c1 = $_POST['choice1'];
    
  12. Using the insert user script as a model, write an if statement so that we will only perform the insert if the submit button was pressed and all the form elements are not blank, i.e. != ""
  13. Use the following PHP code as model for creating your insert query:
    $sql = "INSERT INTO Questions????? (question, choice1, choice2, choice3, choice4, answer) VALUES ('$q','$c1','$c2','$c3','$c4','$a')";
    
  14. Replace ????? with a five digit number you used to make your table.
  15. Use require_once to include your functions.php file
  16. Call your db_connect function and execute the query as follows:
    	$mysqli = db_connect();				
    	$mysqli->query($sql);
    	$mysqli->close();
    
  17. Save insert_question.php
  18. Use WinSCP to connect to the server and upload your lab folder to the server
  19. Type the following URL into your browser:
    http://s123456.sienasellbacks.com/lab8/insert_question.php
    where "s123456" is your userid.
  20. We will verify that this worked soon.

Part 3: Showing all the questions

  1. Use the show_data.php from the previous lab as a model to create a new script called show_questions.php
  2. Note that the only change you need to make is to use the correct table name in the query.
  3. Save show_questions.php
  4. Use WinSCP to connect to the server and upload your lab folder to the server
  5. Use your two scripts to insert two real questions into you table.
  6. Verify that all the fields are correctly inserted.

Part 4: Script Integration

  1. The two scripts you created can be unified into one combined script where after you insert a new question the table of questions is displayed so you can see that the insertion worked.
  2. Think of the insert script as a big if statement where you either (a) generate the form or (b) perform the insertion and then display all the question data. The key is that you also need to generate a hyperlink so you can go back to the form. When you click the hyperlink, the Insert button's value will be null and the form will be regenerated.
  3. Here you can simply cut and paste code from show_questions.php to insert_question.php.

Part 5: Displaying a question

In this part, we will create a script that will randomly selects a question from the database and use it to generate a form for actually submitting an answer to a question.

Your finished form should look like this:
screenshot

Help & Hints:

  1. Use your insert question script as starting document and save it as get_question.php
  2. At the top of the document use PHP code to run the following query:
    SELECT question, choice1, choice2, choice3, choice4 FROM Questions????? ORDER BY RAND()
    
  3. The query above selects all the questions and orders them randomly.
  4. We just have to fetch the first one:
    $row = $result->fetch_row();
    
  5. $row is a regular array that has the five fields we selected. Thus, we can copy them to PHP variables as follows:
    $q = $row[0];
    $c1 = $row[1];
    $c2 = $row[2];
    
  6. In the body of the HTML document, we can generate the form from the PHP variables as follows:
    		<form method="post" action="get_question.php">
    		
    		<label><? echo $q ?><br>
    		</label><br>
    		
    		<label>
    		<? echo $c1 ?>
    		<input type="radio" name="answer" value="1">
    		</label><br>
    
  7. Notice that the form calls itself. In project 4, you will implement the processing of this dynamically generated form, which is complicated because we have to secretly store the answer.

DELIVERABLE

Create a zip file of your lab8 folder called lab8.zip and submit the file in Blackboard.

In the comment area of Blackboard put your partner's name.