Hello I am trying to connect a page to a MySQL database for newsletter signup. I have the database with 3 fields, id, name, email. The database is named newsletter and the table is named newsletter. Everything seems to be fine but I am getting this error
Notice: Undefined index: Name in C:\wamp\www\insert.php on line 12 Notice: Undefined index: Name in C:\wamp\www\insert.php on line 13
Here is my form code.
<form action="insert.php" method="post">
<input type="text" value="Name" name="Name" id="Name" class="txtfield" onblur="javascript:if(this.value==''){this.value=this.defaultValue;}" onfocus="javascript:if(this.value==this.defaultValue){this.value='';}" />
<input type="text" value="Enter Email Address" name="Email" id="Email" class="txtfield" onblur="javascript:if(this.value==''){this.value=this.defaultValue;}" onfocus="javascript:if(this.value==this.defaultValue){this.value='';}" />
<input type="submit" value="" class="button" />
</form>
Here is my insert.php file.
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="newsletter"; // Database name
$tbl_name="newsletter"; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// Get values from form
$name=$_POST['Name'];
$email=$_POST['Email'];
// Insert data into mysql
$sql="INSERT INTO $tbl_name(name, email)VALUES('$name', '$email')";
$result=mysql_query($sql);
// if successfully insert data into database, displays message "Successful".
if($result){
echo "Successful";
echo "<BR>";
echo "<a href='index.html'>Back to main page</a>";
}
else {
echo "ERROR";
}
?>
<?php
// close connection
mysql_close();
?>
The error indicates the index Name
is not found in the $_POST[]
array. It is a PHP notice, and not a show-stopping error, but rather is intended to communicate that you are referencing a value which does not exist. If it is normal/expected that this value might be empty/null then the notice can be safely ignored.
Beyond this problem, you should be sanitizing public values prior to referencing within the SQL statement, ie:
$name = mysql_real_escape_string($_POST['Name']);
$email = mysql_real_escape_string($_POST['Email']);
A few other notes:
In the call to mysql_connect()
it is not necessary to wrap variables $host
, $username
or $password
in quotes. The same is true with $db_name
in call to mysql_select_db()
. They are already strings as defined in the lines above and so this is excessive.
Perhaps some validation on the values in $_POST[]
would be a good idea prior to SQL query? This way you can output an error if, for example, the Name
value is empty.