View Full Version : Problem stopping empty strings being inserted by PHP script

04-18-2012, 05:12 PM
I have a form which allows a backend manager to enter up to 3 email addresses into a simple mySQL table (which has just 2 fields- ID, which is an auto-incrementing primary key, and the Email address field, just a Varchar)

The problem is that as it stands, if they enter just one email address and leave the other two form fields empty, empty values get inserted as new records in the table.

This is the script:

// Grab the data from the first Add a New Email form and assign to variables
$emailaddress = $_POST['_EmailAddress'];
$emailaddress2 = $_POST['_EmailAddress2'];
$emailaddress3 = $_POST['_EmailAddress3'];

// Build SQL Query

$query = "INSERT INTO emailcontacts (Email) VALUES ('$emailaddress'), ('$emailaddress2'), ('$emailaddress3')"; // specify the table and field names for the SQL query

if($result = mysql_query($query))
//go to the new member confirmation page
header('location: admin_confirmed.php');
echo "ERROR: ".mysql_error();

I tried setting different queries based on whether or not the various variables were empty, using if empty and if !empty, but that didn't work.

What I want is for it to just enter new records for when the various form fields and coresponding variables have actual values.

I can't really force the user to enter three new email addresses each time as they may not have that many to add.

Any ideas?

04-18-2012, 09:45 PM
Personally, I would do the following:

// Add all email values to an Array
$emailaddresses = array($_POST['_EmailAddress'], $_POST['_EmailAddress2'], $_POST['_EmailAddress3']);

// Add a counter to determine how many rows added
$counter = 0;

// Loops through each email textbox value
foreach ($emailaddresses as $email){

// If the current textbox has an email in it... then
if($email != ""){
// Add it to the $query string...
$query = "INSERT INTO emailcontacts (Email) VALUES ('$email')";
// ... Insert it into the database (or error/exit script if something is wrong)
if($result = mysql_query($query) or die(mysql_error()))
// ... and increase the counter for tracking purposes

if ($counter > 0){
} else {


Obviously, untested. But in theory should work fine. It basically puts the values into an array and them loops through all three textbox values (encase the user puts an email in the second box but not the first) tests each value to see if it has a value; then inserts it into the database.

The counter allows you to determine the number added if any.


04-19-2012, 03:08 PM
Thanks Jordan- that solution works great pretty much as is, I just put the redirect in the final if statement.