-2

When I click the submit button from the form without entering any values, it displays the message Please fill all the fields and error for the query. But it also generates the following notice:

Notice: Undefined variable: sql in C:\XAMPP\htdocs\statistics\savecourseadminscores.php on line 31

Is this normal?

saveITScores.php

 <?php

 define('DB_NAME','some');//false name
 define('DB_USER','some');//false name
 define('DB_PASSWORD','some');//false name
 define('DB_HOST','localhost');

 $connect = mysql_connect(DB_HOST,DB_USER,DB_PASSWORD);

 if(!$connect){
      die('Could not connect:'.mysql_error());
 }

 $db_selected=mysql_select_db(DB_NAME,$connect);

 if(!$db_selected){
   die('Can\'t use'.DB_NAME.':'.mysql_error());
 }

$value1=$_POST['s1'];
$value2=$_POST['s2'];
$value3=$_POST['year'];

if(isset($_POST['submit'])){

    if($value1 && $value2 && $value3){
       $sql="INSERT INTO itservice(s1,s2,year)    VALUES('$value1','$value2','$value3')";
    }
    else{
       echo "Please fill all the fields.";
    }
}
  if(!mysql_query($sql)){
     die('Error:'.mysql_error());

  }

  mysql_close();

  ?>

saveForm.php

  <div id="form">

<form action="saveITScores.php" method="POST">
S1: <input class="inputfield" type="text" name="s1" size="5"> <br /><br/>
S2: <input class="inputfield" type="text" name="s2" size="5"> <br /><br/>
<b>Year:<b/>
<select name="year"> 
<option value="Choose">Please select..</option>
<option value="2005">2005</option> 
<option value="2006">2006</option>
<option value="2007">2007</option>
<option value="2008">2008</option>
<option value="2010">2010</option>
<option value="2011">2011</option>
<option value="2012">2012</option></select><br/><br/>

<br/>
<input type="submit" value="Save" name="submit">
<input type="reset" name="reset" value="Clear"><br /><br/>
aurora
  • 161
  • 4
  • 15
  • Can you state in your code at which line you seem that notice will generate. And please use mysqli_* or PDOinstead of mysql_* because it is officially deprecated noe. – Alive to die - Anant May 02 '15 at 14:17
  • 2
    `if(!mysql_query($sql)){` <- Look at this if statement and think about it, when you get the output: `Please fill all the fields` when and where the variable `$sql` gets defined – Rizier123 May 02 '15 at 14:18
  • @ anant kumar singh At line 31 in `saveITScores.php` I get this `Notice`. – aurora May 02 '15 at 14:21

1 Answers1

0
<?php 

if(isset($_POST['submit'])){
    $value1=$_POST['s1'];
    $value2=$_POST['s2'];
    $value3=$_POST['year'];

    if(!empty($value1) && !empty($value2) && !empty($value3))
    {
       $sql=mysql_query("INSERT INTO `itservice`(`s1`,`s2`,`year`)VALUES('".$value1."','".$value2."','".$value3."')")or die(mysql_error());
    }
    else{
       echo "Please fill all the fields.";
    }
}

     ?>
Vivek Singh
  • 2,453
  • 1
  • 14
  • 27