Php表单帮助 - 不会发布到数据库

时间:2011-07-12 12:57:29

标签: php webforms

我设计的表格在大约一小时前工作正常。现在无论我做什么,我似乎得到一个错误消息,因为我有一些验证代码来检查是否已完成某些必填字段。

这是我的完整代码:

<! Code to check that the user has logged into to view this page !>
<?php
session_start();
if (!(isset($_SESSION['login']) && $_SESSION['login'] != '')) {
header ("Location: login.php");
}
?>
<!Connection details for connecting to mysql database!>
<?php
$connection = mysql_connect("localhost", "username", "password");

if (!$connection){
 die("database connection failed: " . mysql_error());
 }

//Select which database you want to connect to
$db_select = mysql_select_db("databasename" , $connection);
if (!$db_select){
die("An error occurred: " . mysql_error());
}
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Op Tech Database - Add Record</title>
</head>
<!Code to Create drop down menu's!>
<?php
//Code for collectiing values for Student Names drop down drop
$result1=mysql_query("SELECT studentID, studentName FROM students");
$options1="";
while ($row=mysql_fetch_array($result1)) {

    $id=$row["studentID"];
    $first=$row["studentName"];

    $options1.="<OPTION VALUE=\"$first\">".$first.'</option>';
    }

//Code for getting tutors names in drop down list
$result2=mysql_query("SELECT staffID, tutorName FROM staff");

$options2="";
while ($row=mysql_fetch_array($result2)) {

    $id=$row["staffID"];
    $first=$row["tutorName"];

    $options2.="<OPTION VALUE=\"$first\">".$first.'</option>';
    }
?>
<body>
<link rel="stylesheet" type="text/css" href="ex1.css" >
<link rel="stylesheet" media="only screen and (max-device-width: 1024px)" href="ipad.css" type="text/css" />
<!Create HTML elements!>
<form name="myform" form method="post">
  <h1 align="center"><a href="form.php"><img src="colour_logo_400.jpg" alt="University Logo" width="400" height="185" /></a></h1>
  <h1 align="center">Dental Hygiene Operative Technique Database</h1>
  <h2 align="center">Welcome to the Dental Hygiene Operative Technique Database v1</h2>
  <p align="left">&nbsp;</p>
  <p align="left">Student Name(*)</p>
  <p align="left">
   <! Drop Down Menu to get student names from database !>
    <SELECT NAME=studentName >
        <OPTION VALUE=0 selected="selected" >
            <?php if(isset($_POST['studentName'])) echo $_POST['studentName'];?>
        <?php echo $options1?>
    </SELECT>  

  <p align="left">Tutor Name  
  (*)<p align="left"> 
    <! Drop Down Menu to get tutor names from database !>
    <select name=tutorName>
        <option value=0>
            <?php if(isset($_POST['tutorName'])) echo $_POST['tutorName'];?>
      <?php echo $options2 ?> </option> 

    </select>
  <p align="left">
  <p align="left"><br>


    Procedure(*)
      <input type="text" name="procedure"  value="<?php if(isset($_POST['procedure'])) echo $_POST['procedure'];?>" />

    (*)
  <p align="left">

 Student Reflection:
        (*)<br>
  <textarea name="studentReflection" cols="75" rows="5"><?php if(isset($_POST['studentReflection'])) echo $_POST[               'studentReflection'];?></textarea>  
  <p align="left">
        <select name=grade id=grade>
          <option value="">Grade </option>
          <option value="N" <?php if (isset($_POST['grade']) && $_POST['grade'] == "N") { echo 'selected="selected"';} ?>>N</option>
          <option value="B" <?php if (isset($_POST['grade']) && $_POST['grade'] == "B") { echo 'selected="selected"';} ?>>B</option>
          <option value="C" <?php if (isset($_POST['grade']) && $_POST['grade'] == "C") {   echo 'selected="selected"';} ?>>C</option>
                  </select> 
        (*)
<p align="left">
        <SELECT NAME=professionalism>
          <OPTION VALUE="">Professionalism
          <OPTION VALUE="U" <?php if (isset($_POST['professionalism']) && $_POST['professionalism'] == "U") {
      echo 'selected="selected"';} ?>>U</option>
          <OPTION VALUE="S" <?php if (isset($_POST['professionalism']) && $_POST['professionalism'] == "S") {
      echo 'selected="selected"';} ?>>S</option>
          <OPTION VALUE="E" <?php if (isset($_POST['professionalism']) && $_POST['professionalism'] == "E") {
      echo 'selected="selected"';} ?>>U</option>
        </SELECT>
        </SELECT>

      <SELECT NAME=communication>
        <OPTION VALUE="">Communication
        <OPTION VALUE="U" <?php if (isset($_POST['communication']) && $_POST['communication'] == "U") {
      echo 'selected="selected"';} ?>>U</option>
        <OPTION VALUE="S" <?php if (isset($_POST['communication']) && $_POST['communication'] == "S") {
      echo 'selected="selected"';} ?>>S</option>
        <OPTION VALUE="E" <?php if (isset($_POST['communication']) && $_POST['communication'] == "E") {
      echo 'selected="selected"';} ?>>U</option>
    </SELECT>
       Alert:
        <input type="checkbox" value="YES" name="alert" >  
        <br>
        <br>
        Dispute:
        <input type="checkbox" value="YES" name="dispute">
  <p align="left">Tutor Comments:        
        <p align="left">
          <textarea name="tutorComments" cols="75" rows="5"><?php if(isset($_POST['tutorComments'])) echo $_POST['tutorComments'];?>
        </textarea>
  <p align="left">

<!Submit buttons for the form!>
    Password
   <INPUT TYPE = 'PASSWORD' Name ='password'  value="" maxlength="16" autocomplete="off"><br><br>
     <input type="submit" name="mattbutton" class="mattbutton" value="Update Database"  name="submit"/> 
     <input type='button' name="mattbutton" class="mattbutton" value='Logout' onClick="window.location.href='logout.php'">  
  <input type="hidden" name="submited" value="true" />
  <p align="left">

<?php

//Code to turn off error reporting
//error_reporting(0);

//Error Message to display if all the correct fields are not completed.

if(isset($_REQUEST['submited'])) {

$options1 = $_POST['studentName'];
$options2 = $_POST['tutorName'];
$procedure = htmlspecialchars($_POST['procedure']);
$grade = $_POST['grade'];
$studentReflection = htmlspecialchars($_POST['studentReflection']);
$professionalism = $_POST['professionalism'];
$communication = $_POST['communication'];
$tutorComments = htmlspecialchars($_POST ['tutorComments']);
$masterpass = $_POST['password'];
$dispute = $_POST['dispute'];
$alert = $_POST['alert'] ;

$errors = 'Update Failed:';

//Code to check that the student picked there name  
    if(empty($_POST['studentName'])) 
    {
    $errors .= "You did not enter the student name<br/>";
    }
//Code to check that the Tutor Name field is completed
    if(empty($_POST['tutorName'] ))
    {
    $errors .="You did not select a tutor<br/>";
    }
//Code to check that the Procedure field is completed
    if(empty($_POST['procedure'] ))
    {
    $errors .="You did not enter a procedure<br/>";
    }
//Code to check that the Grade field is completed
    if(empty($_POST['grade'] ))
    {
    $errors .="You did not enter a grade<br/>";
    }
//Code to check that the Student Reflection field is completed
    if(empty($_POST['studentReflection'] ))
    {
    $errors .="You did not enter a reflection<br/>";
    }
//Code to check if the tick box is checked that the tutor comment is entered
    if( !strlen($_POST['tutorComments']) && isset($_POST['alert'] ))
    {
    $errors .="You must enter a reasan why you ticked the alert box";
    }
//Code to check the password field is completed and correct
    if (empty($_POST['password']))
    {
    $errors .="You did not enter you password";
    }

if(!empty($errors))
{
    echo '<h3>' . $errors . '</h3>';
    exit();
    }   
}

if (!empty($_POST['password']))
    {


//==========================================
//  ESCAPE DANGEROUS SQL CHARACTERS
//==========================================
function quote_smart($value, $handle) {

   if (get_magic_quotes_gpc()) {
       $value = stripslashes($value);
   }

   if (!is_numeric($value)) {
       $value = "'" . mysql_real_escape_string($value, $handle) . "'";
   }
   return $value;
}

if ($_SERVER['REQUEST_METHOD'] == 'POST'){

    $masterpass = $_POST['password'];
    $masterpass = htmlspecialchars($masterpass);

    //==========================================
    //  CONNECT TO THE LOCAL DATABASE
    //==========================================
    $user_name = "username";
    $pass_word = "password";
    $database = "databasename";
    $server = "host";

    $db_handle = mysql_connect($server, $user_name, $pass_word);
    $db_found = mysql_select_db($database, $db_handle);

    if ($db_found) {

        $masterpass = quote_smart($masterpass, $db_handle);

        $SQL = "SELECT * FROM masterpass WHERE password = $masterpass";
        $result = mysql_query($SQL);
        $num_rows = mysql_num_rows($result);

    //====================================================
    //  CHECK TO SEE IF THE $result VARIABLE IS TRUE
    //====================================================

        if ($result) {
            if ($num_rows > 0) {
                echo "";
            }
            else {
                echo "Your Password was not recognised";
                exit();
            }   
        }
        mysql_close($db_handle);

    }
}

//===========================================================
//Code to connect to the database and insert the POST values
//===========================================================
mysql_connect ("host", "username" , "password") or die ('Error: ' .mysql_error());
mysql_select_db ("dhoptech2011");

$query= "INSERT INTO entry (entryID, studentName , tutorName , procedureName , grade , studentReflection , tutorComments,  professionalism , communication , alert , dispute ) VALUES ('NULL', '".$options1."' , '".$options2." ' , '".$procedure."' , '".$grade."' , '".$studentReflection."', '".$tutorComments."' , '".$professionalism."' , '".$communication."' , '".$alert."' , '".$dispute."' )";


mysql_query($query) or die ('Error : You are attempting to enter information which cannot be stored or contains code. Please refesh the from and try again<br>' .mysql_error());

echo "<h4>The Database Has been updated. Thanks </h4>" ; 
}
?>

</FORM>
<p>  <a href="form.php">Enter another procedure </a>
<p>&nbsp;</p>
<p>&nbsp;</p>
</body>
</html>

我知道这是很多代码,但我仍然在努力学习最佳实践。

直到大约一个小时前,该表单似乎正在运行,但现在即使我用所有必填字段填写表单,它也不会将信息传递给我的数据库表。

知道我可能出错了吗?

1 个答案:

答案 0 :(得分:1)

您的$errors变量永远不会为空!

您可以将其设置为默认字符串:

$errors = 'Update Failed:';

然后继续执行一堆if语句来检查条件,但是在退出之前,您从来没有else个案例来清除$errors变量:

if(!empty($errors))
{
    echo '<h3>' . $errors . '</h3>';
    exit();  
}

将初始行更改为空字符串。

$errors = '';

然后在完成所有其他检查之后,如果您希望将其添加到开头,可以将Update failed:字符串添加到开头:

if(!empty($errors))
{
    echo "<h3> Update failed: $errors</h3>";
    exit();
}