运行脚本时出现警告

时间:2013-03-28 18:10:02

标签: php html html5

我在运行脚本时收到了这些警告:

Notice: Undefined variable: varName in C:\wamp\www\dash\index.php on line 38
Notice: Undefined variable: varMsg in C:\wamp\www\dash\index.php on line 38
Notice: Undefined variable: varDate in C:\wamp\www\dash\index.php on line 38

此外,我可以在数据库中插入详细信息,但每次刷新页面时都会插入查询。

脚本的重要部分:

<?php
date_default_timezone_set('UTC');

if(isset($_POST['formSumbit']))
{
   $varName = $_POST['formName'];
   $varMsg = $_POST['formMsg'];
   $varDate = date(d/m/y);
   $errorMessage = "";
}
//line 38
 $order ="INSERT INTO dash (name,msg,msg_date) VALUES ('$varName','$varMsg','$varDate')";  
    $result = mysql_query($order); 


?>

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
  name
  <input type="text" name="formName" maxlength="25"  />

  msg
  <input type="text" name="formMsg" maxlength="1500"  />


<input type="submit" name="formSumbit" value="Submit" />
</form>

3 个答案:

答案 0 :(得分:2)

您的if(isset($_POST['formSumbit'])) {}也需要包围查询:

if(isset($_POST['formSumbit']))
{
   $varName = $_POST['formName'];
   $varMsg = $_POST['formMsg'];
   $varDate = date('Y-m-d');
   $errorMessage = "";
   //line 38
   $order ="INSERT INTO dash (name,msg,msg_date) VALUES ('$varName','$varMsg','$varDate')";  
   $result = mysql_query($order); 
}

每次刷新页面时,查询都在运行,但是它们正在插入空值,因为这些值包含在if语句中。这就是你收到通知的原因。您没有这些值,因为表单尚未提交。

答案 1 :(得分:1)

if(isset($_POST['formSubmit']))语句中添加第38行和第39行。目前,当加载页面时,每次都会执行此操作,但是您只想在提交表单时执行它:

if(isset($_POST['formSumbit']))
{
   $varName = $_POST['formName'];
   $varMsg = $_POST['formMsg'];
   $varDate = date(d/m/y);
   $errorMessage = "";
   $order ="INSERT INTO dash (name,msg,msg_date) VALUES ('$varName','$varMsg','$varDate')";  
   $result = mysql_query($order);
}

答案 2 :(得分:0)

将以下代码放入单独的文件(例如“insert.php”)并将操作设置为此,这将解决重复插入问题。

if(isset($_POST['formSumbit']))
{
   $varName = $_POST['formName'];
   $varMsg = $_POST['formMsg'];
   $varDate = date(d/m/y);
   $errorMessage = "";
   $order ="INSERT INTO dash (name,msg,msg_date) VALUES ('$varName','$varMsg','$varDate')";  
   $result = mysql_query($order);
   if($result){
       header("Location: back-to-form.php");
   } else {
      echo mysql_error();
   }
}