Frames Modems Help Home Page Chipsets Search No Frames
Diary Entries See also Site Info & Diary.
18 January 2002 The use of PHP variable Variables...
  Here's the problem:
  1. A PHP file is used to create an HTML page with a Form to collect & submit values which are used by the same PHP file to fill tables within a MySQL database.
  2. The table contains a field which holds a boolean (yes/no) value.
  3. It is desired to not only allow new table entries but to also display existing table entries, and to allow these latter to be changed & updated.
  This wasn't academic for me - one actual example is the Dead field in names (see 14 Jan for the tables & 18 Dec for the Forms class).

Creating the Form controls is easy:

    $dRad1=new Radio("nDead", 1);
    $dRad1->acc="Y";
    $dRad1->lab="Yes";
    $dRad0=new Radio("nDead", 0);
    $dRad0->acc="N";
    $dRad0->lab="No";
    $dRad0->rt=TRUE;
    ...
    $dRad1->show()." ".$dRad0->show()
This creates 2 option buttons with the same name & therefore will toggle on/off when pressed in the HTML page. The variable $nDead will be submitted back to the PHP file and appear with a value of "1" (TRUE) or "0" (FALSE).

All well & good so far, but what happens when you want to display multiple rows from the same table and allow changes? The first thought is perhaps to use something like the following:

    $cHid=new Hidden("nid[]", NULL);
    $r=mysql_query($s);
    while(list($cHid->val,$val)=mysql_fetch_row($r)) {
      $dRad1->chk=($val)?TRUE:NULL;
      $dRad0->chk=($val)?NULL:TRUE;
      ...
      $dRad1->show()." ".$dRad0->show()
    }
Here, $s is a query which returns the NID & Dead fields from the table. The problem is that all the option buttons in the HTML have the same name, so when any button is selected all the others switch off. The sets of buttons need to have unique names, solved as follows:
    while(list($cHid->val,$val)=mysql_fetch_row($r)) {
      $dRad1->nam=$dRad0->nam="nDead".$cHid->val;
      $dRad1->chk=($val)?TRUE:NULL;
      $dRad0->chk=($val)?NULL:TRUE;
      ...
      $dRad1->show()." ".$dRad0->show()
    }
So, as an example, record 111 will give 2 option buttons with a name of "nDead111" - unique in the form. The question then is how to extract the values from the submitted variables, and this is where the variable Variables comes in:
    while(list($key,$val)=each($nName)) {
      $r="nDead".$nid[$key];
      $q=(($nid[$key])?"UPDATE":"INSERT INTO").
      ...
       ", Dead=".((!$$r)?"NULL":"1").
       (($nid[$key])?" WHERE NID=$nid[$key]":"");
      mysql_query($q);
    }
$r is the Variable, and $$r is the variable Variable ($nName[] is another field not shown previously, and is the actual Name). To use the previous example, $nid[$key] will be equal to "111" & $r will be set to a value of "nDead111". $$r then references the variable with the name "nDead111" and this has a value of either "1" or "0". Dead easy, once you catch the way of it, and damn useful.