captcha forms html php validation

Form validation and captcha

I have two issues with a contact form I have created. I was previously hit hard by spam.

  1. I am requiring that all fields be filled out before the form is processed, but what I have written isn’t working: info goes into the database whether a person fills out all fields or not. ***fixed by using:

    function validateForm()
    var x=document.forms[“validation”][“firstname”].value;
    if (x==null || x==””)
    alert(“Please enter your first name”);
    return false;

for all fields and this one for email:

    var x=document.forms["validation"]["email"].value;
var atpos=x.indexOf("@");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
alert("Please enter a valid email address");
return false;

Now, I need to get the captcha working or how to add to check if captcha is correct in same javascript? I think the error lies in this somehow?:

if($_POST['submitted'] == "contactus")
if( $_SESSION['security_code'] == $_POST['security_code'] && !empty($_SESSION['security_code'] ) ) {
} else {
// Insert your code for showing an error message here
echo "<div id='thankyoubox'>'Security breach! Security Breach! Ehem...Your security code was incorrect.'</div>";

And lastly, here is contactfunctions.php

    <?php ob_start();//Required for the redirect to work?>
$contactsdbtable = "contacts";
function GetHeaders()
$headers="MIME-Version: 1.0" . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// Additional headers
$headers .= "To: {$firstname} <{$email}>" . "\r\n";
$headers .= 'From: My Website <[email protected]>' . "\r\n";
return $headers;
function ContactMessage($firstname, $lastname, $email, $message, $location)
global $contactsdbtable;
$firstname = mysql_real_escape_string($firstname);
$lastname = mysql_real_escape_string($lastname);
$email = mysql_real_escape_string($email);
$message = mysql_real_escape_string($message);
$location = mysql_real_escape_string($location);
$result = QuickQuery("INSERT INTO {$contactsdbtable}(firstname, lastname, email, message, location)
VALUES('{$firstname}', '{$lastname}', '{$email}', '{$message}', '{$location}')");
$headers = GetHeaders();
$message = "\"Thank you for contacting us at My Website. We will be answering your website inquiry post haste.\"<br />
<br />
<br />
Best Regards,<br />
<br />
mail($email, "RE: Design Inquiry", $message, $headers);
mail("[email protected]", "Website Inquiry", "{$firstname}, {$email}, has sent a web design inquiry", $headers);

I appreciate any help I receive on this in advance. Also, since this is a lengthy post, would you guys mind listing which issue you are addressing, 1 or 2?