...

View Full Version : PHP Form to Not Require a Field?



IFeelYourPain
08-04-2012, 03:29 AM
I am coding a newsletter script and having a bit of a problem. I wish to store the information in the database for a later use, but I wish to not have the user to be required to enter their name, right now the script errors out with "Column Name can not be null."

I would like the name to be Anonymous if no name is entered, and when no email is entered, I would like it to give the user an error message stating that the email is required, plus currently it is allowing me to enter anything into the email field. I would like this to not be possible. Here is my current scripting.

newsletter.php

<html>
<head>
<title>Newsletter</title>
</head>
<body>
<form id="contact" name="contact" action="contact.php" method="post">
<p><label>Name: <input type="text" id="name" name="name" value="" /></label></p>
<p><label>*Email: <input type="text" id="email" name="email" value="" /></label></p>
<input type="hidden" id="action" name="action" value="submitform" />
<p><input type="submit" id="submit" name="submit" value="Submit" /> <input type="reset" id="reset" name="reset" value="Reset" /></p>
</form>
*Required fields
</body>
</html>

Contact.php

<?php
//include the connection file

require_once('connection.php');

//save the data on the DB and send the email

if(isset($_POST['action']) && $_POST['action'] == 'submitform')
{
//recieve the variables
if($_POST['formSubmit'] == "Submit")
{
$varName = $_POST['name'];
$varEmail = $_POST['email'];
$errorMessage = "";
}
if(empty($varName)) {
$errorMessage .= "<li>You forgot to enter a name!</li>";
}
if(empty($varEmail)) {
$errorMessage .= "<li>You forgot to enter a email!</li>";
}

$name = $_POST['name'];
$email = $_POST['email'];
$ip = gethostbyname($_SERVER['REMOTE_ADDR']);

//save the data on the DB

mysql_select_db($database, $connection);

$insert_query = sprintf("INSERT INTO contacts (name, email, date, ip) VALUES (%s, %s, NOW(), %s)",
sanitize($name, "text"),
sanitize($email, "text"),
sanitize($ip, "text"));

$result = mysql_query($insert_query, $connection) or die(mysql_error());

if($result)
{
//send the email

$to = "webmaster@website.com";
$subject = "New contact from the website";

//headers and subject
$headers = "MIME-Version: 1.0rn";
$headers .= "Content-type: text/html; charset=iso-8859-1rn";
$headers .= "From: ".$name." <".$email.">rn";

$body = "New contact
";
$body .= "Name: ".$name."
";
$body .= "Email: ".$email."
";
$body .= "IP: ".$ip."
";

mail($to, $subject, $body, $headers);

//ok message

echo "You have been signed up for our newsletter!";
}
}

function sanitize($value, $type)
{
$value = (!get_magic_quotes_gpc()) ? addslashes($value) : $value;

switch ($type) {
case "text":
$value = ($value != "") ? "'" . $value . "'" : "NULL";
break;
case "long":
case "int":
$value = ($value != "") ? intval($value) : "NULL";
break;
case "double":
$value = ($value != "") ? "'" . doubleval($value) . "'" : "NULL";
break;
case "date":
$value = ($value != "") ? "'" . $value . "'" : "NULL";
break;
}

return $value;
}
?>

Arcticwarrio
08-04-2012, 08:36 AM
Change it in your database, tick the null box on the name column

IFeelYourPain
08-04-2012, 05:42 PM
Change it in your database, tick the null box on the name column

Ok and now how can I make it so if the field is blank it inserts Anonymous into the database?

AndrewGSW
08-04-2012, 08:26 PM
$name = (isset($_POST['name']) && !empty($_POST['name'])) ? sanitize($_POST['name'], "text") : 'Anonymous';


$insert_query = sprintf("INSERT INTO contacts (name, email, date, ip) VALUES (%s, %s, NOW(), %s)",
$name,
sanitize($email, "text"),
sanitize($ip, "text"));
should do it.

IFeelYourPain
08-04-2012, 08:51 PM
I tried the code and even ticked Null, but I get Unknown column 'Anonymous' in 'field list'

Edit: I removed the change of the $insert_query and it successfully works.


What about emails though. I want it required and would like it to error out saying that email is required and I also do not want them to be able to just enter in anything in the field?

Edit: Actually I believe I got it to work through sanitizing of the email. Does everything here look pretty friendly or is there a better way to do this?

$email = $_POST['email'];
if ( filter_var($email, FILTER_VALIDATE_EMAIL) == TRUE) {
echo 'Valid Email Address';
}
else
{
exit("Invalid Email Address");
}

AndrewGSW
08-04-2012, 09:03 PM
Your sanitize puts 'apostrophes' around the string; so probably..


$insert_query = sprintf("INSERT INTO contacts (name, email, date, ip) VALUES ('%s', %s, NOW(), %s)",
$name,
sanitize($email, "text"),
sanitize($ip, "text"));

IFeelYourPain
08-04-2012, 09:20 PM
Your sanitize puts 'apostrophes' around the string; so probably..


$insert_query = sprintf("INSERT INTO contacts (name, email, date, ip) VALUES ('%s', %s, NOW(), %s)",
$name,
sanitize($email, "text"),
sanitize($ip, "text"));

So not entering a name works, but when submitting a name now:

You entered a valid email address. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Johnny'', 'email@yahoo.com', NOW(), 'XX.XXX.XXX.XXX')' at line 1

Current Code:

<?php
//include the connection file

require_once('connection.php');

//save the data on the DB and send the email

if(isset($_POST['action']) && $_POST['action'] == 'submitform')
{
//recieve the variables
$name = (isset($_POST['name']) && !empty($_POST['name'])) ? sanitize($_POST['name'], "text") : 'Anonymous';
$email = $_POST['email'];
if ( filter_var($email, FILTER_VALIDATE_EMAIL) == TRUE) {
echo 'You entered a valid email address. ';
}
else
{
exit("You entered an invalid email address");
}
$ip = gethostbyname($_SERVER['REMOTE_ADDR']);

//save the data on the DB

mysql_select_db($database, $connection);

$insert_query = sprintf("INSERT INTO contacts (name, email, date, ip) VALUES ('%s', %s, NOW(), %s)",
$name,
sanitize($email, "text"),
sanitize($ip, "text"));

$result = mysql_query($insert_query, $connection) or die(mysql_error());

if($result)
{
//send the email

$to = "webmaster@website.com";
$subject = "New contact from the website";

//headers and subject
$headers = "MIME-Version: 1.0rn";
$headers .= "Content-type: text/html; charset=iso-8859-1rn";
$headers .= "From: ".$name." <".$email.">rn";

$body = "New contact
";
$body .= "Name: ".$name."
";
$body .= "Email: ".$email."
";
$body .= "IP: ".$ip."
";

mail($to, $subject, $body, $headers);

//ok message

echo "You have been signed up for our newsletter!";
}
}

function sanitize($value, $type)
{
$value = (!get_magic_quotes_gpc()) ? addslashes($value) : $value;

switch ($type) {
case "text":
$value = ($value != "") ? "'" . $value . "'" : "NULL";
break;
case "long":
case "int":
$value = ($value != "") ? intval($value) : "NULL";
break;
case "double":
$value = ($value != "") ? "'" . doubleval($value) . "'" : "NULL";
break;
case "date":
$value = ($value != "") ? "'" . $value . "'" : "NULL";
break;
}

return $value;
}
?>

AndrewGSW
08-04-2012, 11:11 PM
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Johnny'', 'email@yahoo.com', NOW(), 'XX.XXX.XXX.XXX')' at line 1

There's extra apostrophes around Johnny added by the sanitize function. So, add them around the word 'Anonymous'


$name = (isset($_POST['name']) && !empty($_POST['name'])) ? sanitize($_POST['name'], "text") : "'Anonymous'";

and amend the SQL to remove them:


$insert_query = sprintf("INSERT INTO contacts (name, email, date, ip) VALUES (%s, %s, NOW(), %s)",
$name,
sanitize($email, "text"),
sanitize($ip, "text"));
This will make it behave consisitently (regardless of whether the text is sanitized or not).

IFeelYourPain
08-05-2012, 12:59 AM
That worked perfectly, thank you! I am now working on the cron end of it. What I would like to do is to email those signed up with a different list in a different table. Kinda like events.

I have no idea if I am explaining this right, but I am slowly learning here.

Right now my coding is manual as I am still learning with connection of the database and sending information. However I would like it to be based on a cron job. I have a separate table called jobs with the title of the job and the date the job will be open. I would like to be able to pull from the job table and get the date every day and if the date is within that time, send a newsletter to my members alerting them that the new job is available.

Here is my job table.

CREATE TABLE IF NOT EXISTS `contacts` (
`id` int(11) NOT NULL auto_increment,
`job` varchar(100) NOT NULL,
`date` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Sending Newsletter</title>
</head>
<body>
<?php
require_once('connection.php');
$connect = @mysql_connect($host, $username, $password) or die (@mysql_error());
$selectdb = @mysql_select_db($database, $connect) or die (@mysql_error());

if(isset($_POST['send'])){
$message = $_POST['newsletter'];
$subject = "Daily Newsletter";
$From = "Discussions <email@email.com>";
$emails = @mysql_query("SELECT * FROM newsletter");
while ($show = @mysql_fetch_array($emails)) {
@mail("$show[email]","$subject",$message,"From: $From");
}
echo"<h3>Newsletter has been Sent!</h3>";
}
?>
<h2>Send Newsletters</h2>
<form action="" method="post" name="newsletter">
<strong>Write Newsletter below:</strong><br />
<textarea name="newsletter" cols="70" rows="25"></textarea><br />
<input type="submit" name="send" id="send" value="Send Newsletter" />
</form>
</body>
</html>

AndrewGSW
08-05-2012, 01:13 AM
I know nothing about cron but.. if you're on a hosted-server check their control panel for something like the attached. I believe you then just need to create a small (tiny) script file that tells it what .php page to load and at what time or date interval.

I assume (sensibly..:)) the .php page would not output any HTML.

But you might want to start a new thread.

IFeelYourPain
08-05-2012, 05:57 PM
I know nothing about cron but.. if you're on a hosted-server check their control panel for something like the attached. I believe you then just need to create a small (tiny) script file that tells it what .php page to load and at what time or date interval.

I assume (sensibly..:)) the .php page would not output any HTML.

But you might want to start a new thread.

Yea I have never messed with cron either, so I'll mess around with it and let you know if I need any help.

Edit:
I decided to scrap submitting to another page and just do it all within the same php page, but for some reason the code isn't working now. Inserting into the name leaves it Anonymous, plus I can't get the ip and date to stick.


<?php
require_once('connection.php');
$connect = @mysql_connect($host, $username, $password) or die (@mysql_error());
$selectdb = @mysql_select_db($database, $connect) or die (@mysql_error());
if(isset($_POST['submit'])){
$name = (isset($_POST['name']) && !empty($_POST['name'])) ? sanitize($_POST['name'], "text") : "'Anonymous'";
$email = $_POST['email'];
$ip = gethostbyname($_SERVER['REMOTE_ADDR']);
if(empty($email)){
echo "you must write your email!";
}else{
@mysql_query("INSERT INTO contacts SET email='$email', name='$name', ip='$ip'");
echo "Thanks, for subscribing to our newsletter";
}
}

function sanitize($value, $type)
{
$value = (!get_magic_quotes_gpc()) ? addslashes($value) : $value;

switch ($type) {
case "text":
$value = ($value != "") ? "'" . $value . "'" : "NULL";
break;
case "long":
case "int":
$value = ($value != "") ? intval($value) : "NULL";
break;
case "double":
$value = ($value != "") ? "'" . doubleval($value) . "'" : "NULL";
break;
case "date":
$value = ($value != "") ? "'" . $value . "'" : "NULL";
break;
}

return $value;
}

?>

AndrewGSW
08-05-2012, 06:06 PM
if(isset($_POST['submit'])) {

The name of your submit button is/was 'send'. I wouldn't check the submit button to confirm submission - as discussed elsewhere on this forum. I use a hidden field named 'submitted' and check if this isset.

Your SQL statement no longer mentions NOW(), so the date field will be left blank.

If testing this locally there may not be a value for REMOTE_ADDR.

AndrewGSW
08-05-2012, 06:15 PM
You might try this:


$myIP = gethostbyname(trim(`hostname`));

IFeelYourPain
08-05-2012, 09:35 PM
You might try this:


$myIP = gethostbyname(trim(`hostname`));

It's on my server. So it did work before, but the reason it is now if(isset($_POST['submit'])){ is because the form is being submitted on the same page now. So when someone clicks submit it does everything in that conditional.
I actually got it to work after correcting a misplaced ";" but I seem to be at another stump. I was trying to figure out how to run two conditionals before going into the main conditional and submitting the data to the database.


if(isset($_POST['submit'])){
$name = (isset($_POST['name']) && !empty($_POST['name'])) ? sanitize($_POST['name'], "text") : "'Anonymous'";
$email = $_POST['email'];
$ip = gethostbyname($_SERVER['REMOTE_ADDR']);
if(empty($email) || (filter_var($email, FILTER_VALIDATE_EMAIL) == TRUE)){
echo "You must write your email!";
}
else if(preg_match('#[^a-z]+$#i', $name)) {
echo "The name can not have symbols or numbers!";
}
else{
mysql_select_db($database, $connection);

$insert_query = sprintf("INSERT INTO contacts (name, email, date, ip) VALUES (%s, %s, NOW(), %s)",
$name,
sanitize($email, "text"),
sanitize($ip, "text"));

$result = mysql_query($insert_query, $connection) or die(mysql_error());
echo "Thanks, for subscribing to our newsletter";
}
}

As you can see I am trying to verify the email entered is in fact correct, and that the name is valid and doesn't contain any symbols or numbers.

However my current code is not working. When I revert to prior code:

if(isset($_POST['submit'])){
$name = (isset($_POST['name']) && !empty($_POST['name'])) ? sanitize($_POST['name'], "text") : "'Anonymous'";
$email = $_POST['email'];
$ip = gethostbyname($_SERVER['REMOTE_ADDR']);
if(empty($email)){
echo "you must write your email!";
}else{
mysql_select_db($database, $connection);

$insert_query = sprintf("INSERT INTO contacts (name, email, date, ip) VALUES (%s, %s, NOW(), %s)",
$name,
sanitize($email, "text"),
sanitize($ip, "text"));

$result = mysql_query($insert_query, $connection) or die(mysql_error());
echo "Thanks, for subscribing to our newsletter";
}
}

It works fine.

AndrewGSW
08-06-2012, 01:21 AM
It's getting let.. but filter_var returns FALSE when the filter fails; that is, if it is not a valid email.

IFeelYourPain
08-06-2012, 04:16 AM
Come again? It's getting let?

IFeelYourPain
08-07-2012, 07:16 AM
It's getting let.. but filter_var returns FALSE when the filter fails; that is, if it is not a valid email.

Ahh yes, ok. I see what you are saying. However even when changed to false. It then displays the error "You must enter an email" So it is skipping the conditional altogether.

AndrewGSW
08-07-2012, 12:24 PM
The message "You must enter an email" does not appear in your recent code, so I assume you've modified it since. So post the current version of your code.

IFeelYourPain
08-07-2012, 04:21 PM
The message "You must enter an email" does not appear in your recent code, so I assume you've modified it since. So post the current version of your code.


if(isset($_POST['submit'])){
$name = (isset($_POST['name']) && !empty($_POST['name'])) ? sanitize($_POST['name'], "text") : "'Anonymous'";
$email = $_POST['email'];
$ip = gethostbyname($_SERVER['REMOTE_ADDR']);
if(empty($email) || (filter_var($email, FILTER_VALIDATE_EMAIL) == TRUE)){
echo "You must write your email!";
}
else if(preg_match('#[^a-z]+$#i', $name)) {
echo "The name can not have symbols or numbers!";
}
else{
mysql_select_db($database, $connection);

$insert_query = sprintf("INSERT INTO contacts (name, email, date, ip) VALUES (%s, %s, NOW(), %s)",
$name,
sanitize($email, "text"),
sanitize($ip, "text"));

$result = mysql_query($insert_query, $connection) or die(mysql_error());
echo "Thanks, for subscribing to our newsletter";
}
}

AndrewGSW
08-07-2012, 04:31 PM
That code would still would result in the error message "You must write your email!" rather than the "You must enter an email" message that you say you are receiving, so I assume there is some other code that you haven't posted.

IFeelYourPain
08-08-2012, 06:03 AM
That code would still would result in the error message "You must write your email!" rather than the "You must enter an email" message that you say you are receiving, so I assume there is some other code that you haven't posted.

I just changed the text. Same code though.

IFeelYourPain
08-10-2012, 01:09 AM
Basically I am trying to get these if conditionals


if(!preg_match("/^[\w-]+$/", $name)) {
echo "Your name can not contain symbols";
}
if (filter_var($email, FILTER_VALIDATE_EMAIL) == FALSE) {
echo "Your email is incorrect";
}



To go inside of the first conditional before it actually goes to else and submits the infomation into the database.

if(isset($_POST['submit'])){
$name = (isset($_POST['name']) && !empty($_POST['name'])) ? sanitize($_POST['name'], "text") : "'Anonymous'";
$email = $_POST['email'];
$ip = gethostbyname($_SERVER['REMOTE_ADDR']);
if(empty($email)){
echo "you must write your email!";
}else{
mysql_select_db($database, $connection);

$insert_query = sprintf("INSERT INTO contacts (name, email, date, ip) VALUES (%s, %s, NOW(), %s)",
$name,
sanitize($email, "text"),
sanitize($ip, "text"));

$result = mysql_query($insert_query, $connection) or die(mysql_error());
echo "Thanks, for subscribing to our newsletter";
}
}


I'm bad with multiple if conditionals, but instead of using
&& or
OR I figured someone else might be able to shine some light, so my error messages would be more customized.

AndrewGSW
08-10-2012, 01:23 AM
Where did $firstNameSignup come from? It hasn't been mentioned before.

The code you present doesn't always agree with the points you raise in your posts :confused:

IFeelYourPain
08-10-2012, 02:57 AM
Where did $firstNameSignup come from? It hasn't been mentioned before.

The code you present doesn't always agree with the points you raise in your posts :confused:

I updated the code, it should have said $name, I thought about requiring last names two but changed my mind and just didn't update the code. Everything is still the same, I've been working on mainly the layout now, since the if conditional is stumping me. Never been good with them.

IFeelYourPain
08-10-2012, 11:31 PM
Any ideas? I was even trying to use OR in the condition, but still no luck.

if(empty($email) OR !preg_match("/^[\w-]+$/", $name) OR filter_var($email, FILTER_VALIDATE_EMAIL) == FALSE){
echo "you must write your email!";
}

IFeelYourPain
08-13-2012, 08:13 AM
Ok I have had time to mess around a bit more and have solved the email problem, so now they can no longer enter in an invalid or blank email, but I am having problems with the name field. I was attempting an else if conditional, but no matter what I enter into the name field I get "Your name can not contain symbols!"


if(isset($_POST['submit'])){
$name = (isset($_POST['name']) && !empty($_POST['name'])) ? sanitize($_POST['name'], "text") : "'Anonymous'";
$email = $_POST['email'];
$ip = gethostbyname($_SERVER['REMOTE_ADDR']);
if(empty($email) || (filter_var($email, FILTER_VALIDATE_EMAIL) == FALSE)){
echo "Your email is invalid or has not been entered!";
}
elseif(!preg_match("/^[\w-]+$/", $name)) {
echo "Your name can not contain symbols!";
}
else{
mysql_select_db($database, $connection);

$insert_query = sprintf("INSERT INTO contacts (name, email, date, ip) VALUES (%s, %s, NOW(), %s)",
$name,
sanitize($email, "text"),
sanitize($ip, "text"));

$result = mysql_query($insert_query, $connection) or die(mysql_error());
echo "Thanks, for subscribing to our newsletter!";
}
}

infoleather
08-22-2012, 08:58 AM
Elsewhere in this forum. I use a hidden field named "submit" and check the isset.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum