简体   繁体   中英

Warnings while running a script

I get those warnings while I run the script:

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

In addition,I can insert details into the databaase but it inserts queries every time I refresh the page.

the important part of the script:

<?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>

Your if(isset($_POST['formSumbit'])) {} needs to surround the query as well:

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); 
}

Each time you refresh the page the queries are running but they are inserting blank values because the values are wrapped in the if statement. This is why you get the notices. You don't have the values because the form isn't submitted yet.

add lines 38 and 39 inside the if(isset($_POST['formSubmit'])) statement. Currently when the page is loaded this is executed every time, however you only want to execute it when the form is submitted:

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);
}

Put the following code into a separate file such as "insert.php" and set your action to this, this will solve the duplicate insert problem.

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();
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM