I have spent days trying to figure this out to no avail. I have checked the PHP docs as well as multiple other form questions regarding the "undefined index" notice and what seems to be the usual solution "isset()" function.
But I cannot work out the solution in my case.
Here is the code:
<form action="" method="post">
<!-- Here are all the form fields -->
<input type="submit" name="send" value="send"/>
</form>
<?php
$con = mysql_connect("#","#","#");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("#", $con);
$sql="
INSERT INTO events (e_date, e_time, e_type, e_name)
VALUES ('$_POST[form_e_date]','$_POST[form_e_time]','$_POST[form_e_type]','$_POST[form_e_name]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con)
?>
The 4 notices occur on the line with the $sql variable starting at "VALUES" and refer to the form_e_date, etc.
I apologize for asking a question that I realize gets somewhat frequently, but I have tried other people's solutions which either do no work for me or else I am not implementing them correctly.
Please help, and please feel free to leave any other constructive feedback about my code as I'm a newbie.
Thanks!
instead of
'$_POST[form_e_date]','$_POST[form_e_time]','$_POST[form_e_type]','$_POST[form_e_name]'
you should NOT use
'$_POST["form_e_date"]','$_POST["form_e_time"]','$_POST["form_e_type"]','$_POST["form_e_name"]'
because of the danger of SQL injection attacks.
you should be using mysql_real_escape_string
to protect yourself against this.
this would be much safer:
if (array_key_exists("form_e_date", $_POST))
$form_e_date = mysql_real_escape_string($_POST["form_e_date"]);
else
$form_e_date = null;
if (array_key_exists("form_e_time", $_POST))
$form_e_time = mysql_real_escape_string($_POST["form_e_time"]);
else
$form_e_time = null;
if (array_key_exists("form_e_type", $_POST))
$form_e_type = mysql_real_escape_string($_POST["form_e_type"]);
else
$form_e_type = null;
if (array_key_exists("form_e_name", $_POST))
$form_e_name = mysql_real_escape_string($_POST["form_e_name"]);
else
$form_e_name = null;
.
.
.
$sql = "INSERT INTO events (e_date, e_time, e_type, e_name) " .
"VALUES ('{$form_e_date}','{$form_e_time}','{$form_e_type}','{$form_e_name}')";