I’m having trouble with the actual insert line. Right now it just inserts a blank row in the table. Am I bringing in the $email line incorrectly (line that starts with “$sql =…”)?
<script>
function validate(form_id,email) {
var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
var address = document.forms[form_id].elements[email].value;
if(reg.test(address) == false) {
alert('Invalid Email Address');
return false;
}
<?php
if (isset($_POST['email']))
{
$email = mysql_real_escape_string($_POST['email']);
mysql_connect(blah) or die(mysql_error());
mysql_select_db(blah) or die(mysql_error());
$sql = "INSERT INTO `email` (`email`) VALUES ('".$email. "')";
mysql_query($sql);
}
?>
}
</script>
<form id="form_id" method="post" action="#" onsubmit="javascript:return validate('form_id','email');">
<input type="text" id="email" name="email" />
<input type="submit" value="Submit" />
</form>
You can’t call mysql_real_escape_string() until AFTER you’ve connected to the database. Otherwise you’ll just get a warning and a boolean FALSE returned.
Change the order of the code to:
This is done because the m_r_e_s() call needs to retrieve version/status information, particularly which characters need to be escaped, and this can’t be done without an active DB connection.