-2

I'm having trouble inserting data into myqsl database from a form using php. This error displays:

enter image description here

Can someone show me what's wrong with this code? I'm using extract ($_POST) to get the input fields from the superglobal $_POST array.Meanwhile when i separate the form code from the php part of code and place them in separate php files it works correctly and the error doesn't display. Can someone shows me what's wrong with executing them in the same php file like this code attached here? Here is my code in php :

<html>  

<html >
<head>
<title></title>
</head>
<body>
<?php



print ("<form action='p.php' method='post'>
    <p>Name
        <input type='text' name='firstname'  />
    </p>
    <p>Surname
        <input type='text' name='lastname' />
    </p>
    <p>Username
        <input type='text' name='username' />
    </p>
    <p>Password
        <input type='password' name='password' />
        <p/>
    <input type='submit' value='Log In'/>
</form>");
extract ($_POST);
if( !($database=mysql_connect("localhost","root",""))||!(mysql_select_db("st_login",$database))  )
   print("Could not connect");
$query = "INSERT INTO login (firstname, lastname, username,password) VALUES ('$firstname', '$lastname', '$username','$password')";
if(isset($_POST['firstname'] )&&isset($_POST['lastname'])&&isset($_POST['username'])&&isset($_POST['password']) ){
$firstname=$_POST['firstname'];
$lastname=$_POST['lastname'];
$username=$_POST['username'];
$password=$_POST['password'];
}


if ( !empty($firstname)&&!empty($lastname)&&!empty($username) &&!empty($password) ){
  if(!($result=mysql_query($query,$database)))
{
    print("Could not execute query");
    die (mysql_error());//ose error
}
else echo "You are logged in successfully";
}
else echo "Fill in all the blank fields";
mysql_close($database);
?>
</body>
</html>

John Dow
  • 47
  • 2
  • 7

1 Answers1

0

You need to get the input fields from the superglobal $_POST array, it will not automatically appear as local variables, like your $firstname.

So when your form is submitted there should be something like this before you work with it:

$firstname = isset($_POST['firstname']) ? $_POST['firstname'] : '';

And for the other variables as well of course.

ArSeN
  • 5,133
  • 3
  • 19
  • 26
  • Please add your code so we can see what is going on. – ArSeN Jan 02 '16 at 18:06
  • Thank you. The point I made is still valid, in a bit of a different way. If your form was not submitted, you still use the variables, which do not exist. One solution would be to move the definition of your query (`$query = ...`) inside of the if-statement that is right below it. At the end if it, to be precise. This way, the variables are definitively set and you should get rid of the notices. – ArSeN Jan 02 '16 at 19:22
  • @EldaBacka It is always appreciated if you click on "accept" for the answer that solved your problem ;) – ArSeN Jan 02 '16 at 20:07