Using PHP to save form data to a database
A simple on-line experiment

In this example, we implement a (trivally) simple between-subjects experiment as an XHTML form, using a Mysql database to store the data. The following Mysql commands were used to create the table on the server:


     use orval;
     show tables;
     CREATE TABLE expdata1 (
       subNum INT(10) UNSIGNED DEFAULT '0' NOT NULL AUTO_INCREMENT,
       PRIMARY KEY (subNum),
       name VARCHAR(40),
       id VARCHAR(20),
       condition VARCHAR(2),
       answer1 TEXT,
       answer2 TEXT
     );
     show tables;
     quit;                  
  

The following Mysql commands were used to create the database experiment1_stimuli which contains the stimuli for the experiment - 2 versions of each of the two items.

CREATE TABLE experiment1_stimuli
   (condition VARCHAR(2), item VARCHAR(2), question TEXT);
INSERT INTO experiment1_stimuli VALUES
   ("1", "1", "Do you like short questions?");
INSERT INTO experiment1_stimuli VALUES
   ("2", "1", "Do you like long questions?");
INSERT INTO experiment1_stimuli VALUES
   ("2", "2", "Do you like long answers?");
INSERT INTO experiment1_stimuli VALUES
   ("1", "2", "Do you like short answers?");
SELECT * FROM experiment1_stimuli ;  

The following piece of PHP code accesses the database to get the most recent subject number, and then assigns a value to the variable $condition based on that number:

  <?php 
     $db = mysql_connect("localhost", "orval");
     mysql_select_db("orval",$db);
     $result = mysql_query ('SELECT MAX(subNum) FROM expdata1', $db); 
     $previousSubNum = 0;
     if ($result) $previousSubNum = mysql_result($result,0,"MAX(subNum)");
     $condition = ($previousSubNum % 2) + 1;
  ?>

The previous subject number was , therefore the condition is .


The next section of PHP code gets the stimuli from the database experiment1_stimuli based on the condition:

   
  <?php
     $sql = 'SELECT question FROM experiment1_stimuli WHERE condition = ' . $condition;
     $stimuli = mysql_query ($sql, $db);
     $item1 = mysql_result($stimuli,0,"question");
     $item2 = mysql_result($stimuli,1,"question");
  >>

The form in the next section collects the data, and uses another php script (experiment1-storeData.php) to store the data to the database.


Experiment 1


/>