For explanation, you get "Undefined index:
whatever when you try to specify an element of an array that doesn't exist. In your case, you are trying to load up $_GET elements that don't exist UNTIL you submit the form.
The generalized check would be:
Code: Select all
if (isset($array_name['element_key']) {
// do what you want with $array_name['element_key']
}
However, when you have a bunch of items that need checked, and they are all depending on one common condition (in your case, form submitted), you should just wrap the whole section with that check (
if (count($_GET)>0) { ... now use them all, but still no guarentee they all exist)
Additonally in your code, you are directly using variables that are user settable ($_POST,$_GET,$_COOKE, and some $_SERVER are ALL variables to not directly use in output or writing to a database!). At the very least, wrap them with
htmlspecialchars($var,ENT_QUOTES) for output (including in
value="" for forms) and
mysql_real_escape_string() for adding to a query.
Lastly, here is your code, as you have given it, the way I would have coded it. It is cleaned up, provides checks, and allows for better "error checking" (not just an error and having to hit BACK, it is right in the form with what you already entered.). It is also done in a way that will get you moving closer to a MVC mindset, in that all processing is done at the top, and then output is down at bottom. As you can see, doing it this way makes it easier to change the HTML later.
I am also a fan of functions for repetitive things, like echoing out the inputs/selects. Hand coding these, if you change your form to say, add another course, you would have to edit HTML code that has it. In my version, all you have to do is adjust the list at the top of the page.
Code: Select all
<?php
$aryList = array(); // Contain list of items for SELECTS
$aryList['Gender'] = array('Male'=>'Male','Female'=>'Female');
$aryList['Status'] = array('Single'=>'Single','Married'=>'Married','Widow'=>'Widow','Separated'=>'Separated');
$aryList['Course'] = array('course1'=>'Educ','course2'=>'IT','course3'=>'Busi','course4'=>'Eng','course5'=>'Mgt');
$aryList['Year'] = array(1=>'1st',2=>'2nd');
$aryData = array('Name'=>'','Cp'=>'','Email'=>'','Address'=>'','Gender'=>'','Status'=>'','Course'=>'','Year'=>''); // Holds data used by form
$aryErr = array(); // Holds errors on form
$bFormSubmitted = (count($_POST)>0);
if($bFormSubmitted) {
// Form submitted
foreach($aryData as $key=>$val) {
if(isset($_POST[$key])) { $aryData[$key]=trim($_POST[$key]); }
}
// BEGIN: Validate Data
if(strlen($aryData['Name'])<4) {
$aryErr['Name'] = 'Name must be at least 4 characters';
}
if(!preg_match('/^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,6}$/i',$aryData['Email'])) {
$aryErr['Email'] = 'Please enter a valid e-mail address';
}
// Other checks you need here, use similar to 'Name' one above.
// END: Validate Data
$bHasErrors = (count($aryErr)>0);
if (!$bHasErrors) {
// All data validated, so do something with it.
$db = mysql_connect("localhost","root", "")
or die('Could not connect to database server');
mysql_select_db($database)
or die('Could not use database specified');
$SQL1 = 'INSERT INTO `stdinfo` (';
$SQL2 = ') VALUES (';
foreach($aryData as $key=>$val) {
$SQL1 .= '`std'.strtolower($key).'`,';
$SQL2 .= '"'.mysql_real_escape_string($val).'",';
}
// NOTE: this assumes you have a field called 'stdadded' which is type DATETIME so you know when record was added...
// other wise do substr($SQL1,0,-1).substr($SQL1,0,-1).')'
mysql_query($SQL1.'stdadded'.$SQL2.'NOW())')
or die('Error running query: '.mysql_error());
} // END: if(!$bHasErrors)
} // END: if($bFormSubmitted)
// FUNCTIONS TO SIMPLY HTML CODING FOR FORM
function echoSelect($strItem,$strOther='') {
global $aryList,$aryData;
if (!isset($aryList[$strItem])) {
echo '[ERROR: List "'.$strList.'" does not exist]';
} else {
echo '<select name="opt'.$strItem.'" id="opt'.$strItem.'" '.$strOther.'>';
echo '<option value="0" style="font-style: italic;">-- SELECT --</option>';
foreach($aryList[$strItem] as $key=>$val) {
echo '<option value="'.htmlspecialchars($key,ENT_QUOTES).'" ';
if ($aryData[$strItem]==$key) { echo 'selected="selected" '; }
echo '>'.htmlspecialchars($val,ENT_QUOTES).'</option>';
}
echo '</select>';
} }
function errorOut($strItem,$intCols=2) {
global $aryErr;
if (isset($aryErr[$strItem])) {
echo '<tr><td colspan="'.$intCols.'" class="frmErr">'.htmlspecialchars($aryErr[$strItem],ENT_QUOTES).'</td></tr>';
} }
function echoInput($strItem,$strType='text') {
global $aryData;
echo '<input type="'.$strType.'" name="txt'.$strItem.'" id="txt'.$strItem.'" value="'.htmlspecialchars($aryData[$strItem],ENT_QUOTES).'" />';
}
?><html>
<head>
<title> Enrollment form </title>
<body>
<h2> Add student </h2>
<?php if($bFormSubmitted && !$bHasErrors): ?>
<p>Thank you for submitting your information. Yadda, Yadda, Yadda...</p>
<?php else: // if($bFormSubmitted && !$bHasErrors) ?>
<?php if($bFormSubmitted && $bHasErrors): ?>
<p class="frmErr">We have found problem(s) with the form. Please correct and try again.</p>
<?php endif; ?>
<form name="frmEnroll" id="frmEnroll" action="#" method="post">
<table>
<?php echoOut('Name'); ?>
<tr>
<td align="right"><label for="txtName">Student Name:</label></td>
<td><?php echoInput('Name'); ?></td>
</tr>
<?php echoOut('Cp'); ?>
<tr>
<td align="right"><label for="txtCp">Cellphone #:</label></td>
<td><?php echoInput('Cp'); ?></td>
</tr>
<?php echoOut('Email'); ?>
<tr>
<td align="right"><label for="txtEmail">Email Address:</label></td>
<td><?php echoInput('Email'); ?></td>
</tr>
<?php echoOut('Address'); ?>
<tr>
<td align="right" valign="top"><label for="txtAddress">Address:</label></td>
<td>
<textarea rows="5" cols="20" name="txtAddress" id="txtAddress"><?php echo htmlspecialchars($aryData['txtAddress'],ENT_QUOTES); ?></textarea>
</td>
</tr>
<?php echoOut('Gender'); ?>
<tr>
<td align="right"><label for="optGender">Gender:</label></td>
<td><?php echoSelect('Gender'); ?></td>
</tr>
<?php echoOut('Stat'); ?>
<tr>
<td align="right"><label for="optStat">Civil Status:</label></td>
<td><?php echoSelect('Stat'); ?></td>
</tr>
<?php echoOut('Course'); ?>
<tr>
<td align="right"><label for="optCourse">Course:</label></td>
<td><?php echoSelect('Course'); ?></td>
</tr>
<?php echoOut('Year'); ?>
<tr>
<td align="right"><label for="optYear">Year:</label></td>
<td><?php echoSelect('Year'); ?></td>
</tr>
<tr>
<td align="right"><input type="submit" value="Save" name="btnSubmit" /></td>
<td><input type="reset" value="Reset" name="btnSubmit" /></td>
</tr>
</table>
</form>
<?php endif; // END-ELSE: if($bFormSubmitted && !$bHasErrors) ?>
</body>
</html>