Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Page 1 of 2 12 LastLast
Results 1 to 15 of 27
  1. #1
    Regular Coder
    Join Date
    Sep 2007
    Posts
    264
    Thanks
    19
    Thanked 0 Times in 0 Posts

    PHP Form to Not Require a Field?

    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
    Code:
    <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
    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
    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;
    }
    ?>

  • #2
    Regular Coder Arcticwarrio's Avatar
    Join Date
    May 2012
    Location
    UK
    Posts
    738
    Thanks
    20
    Thanked 85 Times in 85 Posts
    Change it in your database, tick the null box on the name column
    There are 10 types of people on CodingForums,
    Those who understand Binary and those who dont.
    Get Cloud Hosting now from only£59 / month

  • #3
    Regular Coder
    Join Date
    Sep 2007
    Posts
    264
    Thanks
    19
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by Arcticwarrio View Post
    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?

  • #4
    Senior Coder
    Join Date
    Apr 2011
    Location
    London, England
    Posts
    2,120
    Thanks
    15
    Thanked 354 Times in 353 Posts
    PHP Code:
    $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.
    "I'm here to save your life. But if I'm going to do that, I'll need total uninanonynymity." Me Myself & Irene.
    Validate your HTML and CSS

  • #5
    Regular Coder
    Join Date
    Sep 2007
    Posts
    264
    Thanks
    19
    Thanked 0 Times in 0 Posts
    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?
    Code:
    $email = $_POST['email'];
    	if ( filter_var($email, FILTER_VALIDATE_EMAIL)  == TRUE) {
    	echo 'Valid Email Address';
    	}
    	else
    	{
    	exit("Invalid Email Address");
    	}
    Last edited by IFeelYourPain; 08-04-2012 at 10:00 PM.

  • #6
    Senior Coder
    Join Date
    Apr 2011
    Location
    London, England
    Posts
    2,120
    Thanks
    15
    Thanked 354 Times in 353 Posts
    Your sanitize puts 'apostrophes' around the string; so probably..

    PHP Code:
    $insert_query sprintf("INSERT INTO contacts (name, email, date, ip) VALUES ('%s', %s, NOW(), %s)",
                                
    $name,
                                
    sanitize($email"text"),
                                
    sanitize($ip"text")); 
    "I'm here to save your life. But if I'm going to do that, I'll need total uninanonynymity." Me Myself & Irene.
    Validate your HTML and CSS

  • #7
    Regular Coder
    Join Date
    Sep 2007
    Posts
    264
    Thanks
    19
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by AndrewGSW View Post
    Your sanitize puts 'apostrophes' around the string; so probably..

    PHP Code:
    $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:
    Code:
    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:
    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;
    }
    ?>

  • #8
    Senior Coder
    Join Date
    Apr 2011
    Location
    London, England
    Posts
    2,120
    Thanks
    15
    Thanked 354 Times in 353 Posts
    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'

    PHP Code:
    $name = (isset($_POST['name']) && !empty($_POST['name'])) ? sanitize($_POST['name'], "text") : "'Anonymous'"
    and amend the SQL to remove them:

    PHP Code:
    $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).
    "I'm here to save your life. But if I'm going to do that, I'll need total uninanonynymity." Me Myself & Irene.
    Validate your HTML and CSS

  • Users who have thanked AndrewGSW for this post:

    IFeelYourPain (08-05-2012)

  • #9
    Regular Coder
    Join Date
    Sep 2007
    Posts
    264
    Thanks
    19
    Thanked 0 Times in 0 Posts
    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.
    Code:
    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 ;
    Code:
    <!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>

  • #10
    Senior Coder
    Join Date
    Apr 2011
    Location
    London, England
    Posts
    2,120
    Thanks
    15
    Thanked 354 Times in 353 Posts
    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.
    Attached Thumbnails Attached Thumbnails PHP Form to Not Require a Field?-cron1.png  
    "I'm here to save your life. But if I'm going to do that, I'll need total uninanonynymity." Me Myself & Irene.
    Validate your HTML and CSS

  • #11
    Regular Coder
    Join Date
    Sep 2007
    Posts
    264
    Thanks
    19
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by AndrewGSW View Post
    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.

    Code:
    <?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;
    }
    
    ?>

  • #12
    Senior Coder
    Join Date
    Apr 2011
    Location
    London, England
    Posts
    2,120
    Thanks
    15
    Thanked 354 Times in 353 Posts
    PHP Code:
    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.
    "I'm here to save your life. But if I'm going to do that, I'll need total uninanonynymity." Me Myself & Irene.
    Validate your HTML and CSS

  • #13
    Senior Coder
    Join Date
    Apr 2011
    Location
    London, England
    Posts
    2,120
    Thanks
    15
    Thanked 354 Times in 353 Posts
    You might try this:

    Code:
    $myIP = gethostbyname(trim(`hostname`));
    "I'm here to save your life. But if I'm going to do that, I'll need total uninanonynymity." Me Myself & Irene.
    Validate your HTML and CSS

  • #14
    Regular Coder
    Join Date
    Sep 2007
    Posts
    264
    Thanks
    19
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by AndrewGSW View Post
    You might try this:

    Code:
    $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.

    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";
    	}
    }
    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:
    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.

  • #15
    Senior Coder
    Join Date
    Apr 2011
    Location
    London, England
    Posts
    2,120
    Thanks
    15
    Thanked 354 Times in 353 Posts
    It's getting let.. but filter_var returns FALSE when the filter fails; that is, if it is not a valid email.
    "I'm here to save your life. But if I'm going to do that, I'll need total uninanonynymity." Me Myself & Irene.
    Validate your HTML and CSS


  •  
    Page 1 of 2 12 LastLast

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •