making a field required
Posted: Thu Feb 05, 2009 2:02 pm
I have a simple form to collect name and email, but i would like to have the fields required. I have already started to get a bunch of empty records in my database. I have tried a couple things, but i keep getting errors.
here is the code as it works, but with nothing required:
here is one example of a way i tried to make it required for name, but im missing something simple im sure... any help would be appreciated:
bad code:
so the
if (!isset($_POST['name']) || $_POST['name'] == ''){
error('You did not enter anything in the name field.');
}
is obviously wrong, any ideas?
thanks in advance,
michael
here is the code as it works, but with nothing required:
Code: Select all
<?php
$con = mysql_connect("localhost","username","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("dbname", $con); //Replace with your MySQL DB Name
$name=mysql_real_escape_string($_POST['name']); //This value has to be the same as in the HTML form file
$email=mysql_real_escape_string($_POST['email']); //This value has to be the same as in the HTML form file
$sql="INSERT INTO freeemails (name,email) VALUES ('$name','$email')"; /*form_data is the name of the MySQL table where the form data will be saved.
name and email are the respective table fields*/
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
mysql_close($con);
?>
bad code:
Code: Select all
<?php
$con = mysql_connect("localhost","username","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("dbname", $con); //Replace with your MySQL DB Name
$name=mysql_real_escape_string($_POST['name']); //This value has to be the same as in the HTML form file
$email=mysql_real_escape_string($_POST['email']); //This value has to be the same as in the HTML form file
$sql="INSERT INTO freeemails (name,email) VALUES ('$name','$email')"; /*form_data is the name of the MySQL table where the form data will be saved.
name and email are the respective table fields*/
if (!isset($_POST['name']) || $_POST['name'] == ''){
error('You did not enter anything in the name field.');
}
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
mysql_close($con);
?>
so the
if (!isset($_POST['name']) || $_POST['name'] == ''){
error('You did not enter anything in the name field.');
}
is obviously wrong, any ideas?
thanks in advance,
michael