<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<title>Using PHP with Forms Example</title>
<style type="text/css">
<!--
body, td, textarea, input, select {font-family:Helvetica; font-size:11px}
th (font-family:Helvetica; font-size:12px}
-->
</style>
</head>
<body>
<?php
$update="";
$refresh="";
//Messages from View source and See DB contents
extract($_GET);
//Populate the data array from the form information
extract($_POST);
///////////////
// If $display is set, just display the source and quit
// (ie. if someone clicked on the "View the Source" link
//
if ( isset($display) ) {
//ereg("([^/]+)$", $PHP_SELF, $match); //Match from last slash to end (just filename)
show_source("form.php"); //Show the source
print "</body></html>"; // finish the HTML
exit; // and quit
} // end if ( isset...
//////////////
// Include the username and password
// These files are stored outside the server path and use a .php
// extention so there is no way a browser will ever display them.
//
// Then connect to the server and pick the database
include '../../../PHP_Includes/pwf.inc.php'; //this path is server dependent
$link = mysqli_connect('mysql.davevogel.com', $user, $pw, 'web_builders')
or die("Can't connect to MySQL server");
//////////////
// The following executes only if the show_database variable is set
// (ie. someone clicked on the "See the Contents of the Database" link
//
// It displays the contents of the database and quits
//
if ( isset($show_database) ) {
$result = mysqli_query($link, "select * from form_example order by id")
or die("Can't query");
print "<h3 align=\"center\">Database Contents</h3>
<div align=\"center\">
<table summary=\"Display database contents\" width=\"650\" border=\"1\">
<tr><th>Id</th><th>Name</th><th>Sex</th><th>Birth Month</th>
<th>Message</th><th>PHP</th><th>PERL</th><th>JavaScript</th><th>HTML</th><tr>";
for ($n=0; $n<mysqli_num_rows($result); $n++) {
$line = mysqli_fetch_array($result);
extract($line);
print "<tr><td align=\"center\">$id</td><td>$name</td><td align=\"center\">$sex</td>
<td align=\"center\">$birth_month</td><td align=\"center\">$message</td>
<td align=\"center\">$python</td><td align=\"center\">$perl</td>
<td align=\"center\">$js</td><td align=\"center\">$html</td></tr>";
} //end for ($n=0...
print "</tr></table></div>";
exit;
}
?>
<h3 align="center">Example of Using PHP/MySQL with forms<br>
<span style="font-size:.70em">(Click to <a href="<?php print "form.php?display=1"; ?>">
View the Source</a> or to <a href="<?php print "form.php?show_database=1"; ?>">
See the Contents of the Database</a>)<br>
(You should also View->Source of this page to see what HTML is generated)</span><br>
<span style="font-size:0.6em">Feel free to make changes and 'Update DB'
to see it work</span></h3>
<!-- Note this form calls itself (action = "") -->
<form action="" method="post">
<div align="center">
<table width="700" cellpadding="5" border="1" summary="Form to view and update data">
<!-- Header Row -->
<tr>
<th>Name</th><th>Sex</th><th>Languages</th><th>Birth Month</th><th>Message</th>
</tr>
<!-- Rest of the table -->
<?php
//////////////
// If "Update DB" button ($update is set) then write
// the form data to the database. All the database information
// is in the $row array in the format: $row[$row number][field name]
// and came from the the form when we pushed the 'Update DB' button.
// All the data is written back, whether it was changed or not
// one row at a time.
//
// Updated 11/21/23 to avoid warnings for unknown array keys
if ($update) {
for ($n=0; $n<sizeof($row); $n++) {
$message = addslashes($row[$n]['message']);
$query = "update form_example set name='{$row[$n]['name']}',
sex='{$row[$n]['sex']}', birth_month='{$row[$n]['birth_month']}',
message='$message'";
if (isset($row[$n]['python'])) $query = $query . ", python='{$row[$n]['python']}'";
else $query = $query . ", python=''";
if (isset($row[$n]['perl'])) $query = $query . ", perl='{$row[$n]['perl']}'";
else $query = $query . ", perl=''";
if (isset($row[$n]['js'])) $query = $query . ", js='{$row[$n]['js']}'";
else $query = $query . ", js=''";
if (isset($row[$n]['html'])) $query = $query . ", html='{$row[$n]['html']}'";
else $query = $query . ", html=''";
$query = $query . " where id=$n";
//echo "$query<br />";
mysqli_query($link, $query)
or die("Can't update - ".mysqli_error($link) );
} // end for ($n=0; $n<sizeof($row)...
} // end if ($update)...
//////////////
// Read the data from the database if 'Read from DB' button pushed, and
// after a DB update with 'Update DB' button but NOT if 'Refresh' button
// was pushed.
//
// The query is: SELECT * FROM form_example ORDER BY id;
// which says select all fields in all rows (since no "where" clause)
// in order by the 'id' number.
//
// The whole database is read into an array of arrays ($row)
// each form tag element is named as row[row number][field type].
// The row number is a sequential numeric and the field type is
// id, name, sex, birth_month, message, php, perl, js, or html
// so the first field of the first row is row[0][id] and so on.
// The PHP variable that will be created from this is $row[0][id]
//
if (!$refresh) { //Get DB data if not a "Refresh"
$result = mysqli_query($link, "select * from form_example order by id")
or die("Can't query");
for ($entry=0; $entry<mysqli_num_rows($result); $entry++ ) {
$row[$entry] = mysqli_fetch_array($result, MYSQLI_ASSOC);
}
}
//////////////
// Note that if we are just 'refreshing', the data comes from the form, NOT
// from the database. This is just to show that the benefit of naming your
// variables the same as the 'name' attribute in the form tags (ie. you are
// using PHP to set the default value of the form field with the values in the
// fields.
//
// A text box (and textarea) can simply have its default value set to the its
// contents but it is a little more difficult to get the value back into a radio
// button, select menu and a check box.
for ($entry=0; $entry<sizeof($row); $entry++) { //For each row of data
// unset($selected); //This generates an undefined variable warning below
$selected['M'] = ''; // this fixes it - 11/21/23
$selected['F'] = '';
//This technique is needed
if ($row[$entry]['sex'] == 'M')
$selected['M'] = 'checked'; // so that the appropriate radio
else $selected['F'] = 'checked'; // button can be 'checked' each radio button has
// a print "$selected[M]" (or F). If the button
// is supposed to be selected the variable prints
// 'selected' otherwise it prints '' (nothing)
// unset($option); //Ditto above, to fix warning 11/21/21
for ($n=1; $n<=12; $n++) { //
$option[$n] = ''; //
}
//A similar technique is used
$option[$row[$entry]['birth_month']] // for a select pull down menu
= 'selected';
$language_array =
array('python', 'perl', 'js', 'html'); //List of the languages
foreach($language_array as $value) { //Ditto, again, for the checkboxes
if (isset($row[$entry][$value]) &&
$row[$entry][$value] == 'Y')
$checkbox[$value] = 'checked';
else $checkbox[$value] = '';
}
?>
<!-- Now all the preliminary stuff is done, let's print the table with the form fields
filled with the default data. Note that the form values have 'name' attributes of the
form: row[row number][form field] so the end up being put into an array of arrays in
PHP.
11/21/23:
Current versions of PHP give a Warning if associative arrays don't have the key names
in quotes. But it only seems to work correctly if in the HTML form the
key values are not quoted. For example:
use row[row_value][key_value]
in the HTML form name attribute but in PHP refer to this variable as:
$row[row_value]['key_value']
-->
<tr>
<!-- Name Text Input Field -->
<td align="center"><input type="text" name="row[<?php print $entry; ?>][name]"
value="<?php print $row[$entry]['name']; ?>"></td>
<!-- M/F Sex Radio Input Field $selected[..] is either 'checked' or '' -->
<td align="center"><input type="radio" name="row[<?php print $entry ?>][sex]"
value="M"<?php print" $selected[M]"; ?>>M<br>
<input type="radio" name="row[<?php print $entry ?>][sex]"
value="F"<?php print" $selected[F]"; ?>>F</td>
<!-- Languages Checkbox Input Field -->
<td style="padding-left:15px">
<input type="checkbox" name="row[<?php print $entry ?>][python]"
value="Y"<?php print " {$checkbox['python']}"; ?>>Python<br>
<input type="checkbox" name="row[<?php print $entry ?>][perl]"
value="Y"<?php print " {$checkbox['perl']}"; ?>>PERL<br>
<input type="checkbox" name="row[<?php print $entry ?>][js]"
value="Y"<?php print " {$checkbox['js']}"; ?>>JavaScript<br>
<input type="checkbox" name="row[<?php print $entry ?>][html]"
value="Y"<?php print " {$checkbox['html']}"; ?>>HTML</td>
<!-- Birth Month Select Menu Field -->
<td align="center"><select name="row[<?php print $entry ?>][birth_month]">
<option value="1"<?php print " $option[1]"; ?>>January</option>
<option value="2"<?php print " $option[2]"; ?>>February</option>
<option value="3"<?php print " $option[3]"; ?>>March</option>
<option value="4"<?php print " $option[4]"; ?>>April</option>
<option value="5"<?php print " $option[5]"; ?>>May</option>
<option value="6"<?php print " $option[6]"; ?>>June</option>
<option value="7"<?php print " $option[7]"; ?>>July</option>
<option value="8"<?php print " $option[8]"; ?>>August</option>
<option value="9"<?php print " $option[9]"; ?>>September</option>
<option value="10"<?php print " $option[10]"; ?>>October</option>
<option value="11"<?php print " $option[11]"; ?>>November</option>
<option value="12"<?php print " $option[12]"; ?>>December</option>
</select></td>
<!-- Message Textarea Input Field -->
<td align="center"><textarea cols="30" rows="8"
name="row[<?php print $entry ?>][message]">
<?php print $row[$entry]['message']; ?></textarea></td>
</tr>
<?php
} // end for ($entry=0; $n<sizeof($row)... to ~line 153
?>
<!-- Start of sub-table containing the buttons -->
<tr><td colspan="5">
<table summary = "Sub-table holding submission buttons">
<tr>
<!-- The Refresh button sends the form data back to the form, if you made changes, the
changes stay on the form but are NOT stored to the database.
-->
<td width="16%">Refresh just sends the values from the form back to the form</td>
<td width="16%" align="left"><input type="submit" name="refresh" value="Refresh"></td>
<!-- The 'Read from DB' button reads back the data from the database and refills the form
with that data. If you made changes, they are lost as the form reflects the stored
database data again.
-->
<td width="16%">Reread the data from the database</td>
<td width="16%" align="left" colspan="2"><input type="submit"
name="read_db" value="Read from DB"></td>
<!-- The 'Update' button commits the changes on the form to the database
-->
<td width="16%">Store the above form values to the database</td>
<td width="16%" align="left"><input type="submit" name="update" value="Update DB"></td>
</tr>
</table> <!-- End of submission button sub-table -->
</td></tr>
</table><!-- End of main table -->
</div>
</form>
</body>
</html>