SitePoint Sponsor

User Tag List

Page 1 of 2 12 LastLast
Results 1 to 25 of 27
  1. #1
    SitePoint Member
    Join Date
    Feb 2012
    Posts
    24
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Errors in my form, please help

    Hi,

    I'm building a form in PHP which captures the data into a MySQL database. Once the user has completed the form it is meant to redirect them to a thankyou.php page. I've put in some validation onto the form, but am getting errors and can't seem to fix them, hence asking for your help. I'm pretty new to PHP so please excuse if I'm asking any silly questions.

    So, I have 3 pages, a form.php, functions.php and db-connetion.php.

    form.php
    PHP Code:
    <?php

    require_once('db-connection.php');
    include(
    'functions.php');

    $NAME cleanInput($conn$_POST['NAME']);  // line 6
    $EMAIL cleanInput(trim($conn$_POST['EMAIL'])); // line 7
    $COMMENTS cleanInput($conn$_POST['COMMENTS']); // line 8

    // date
    $DATE date(cleanInput("Y-m-d"$conn));

    $errors = array();

    // If request is a form submission
    if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    // Validation
    // Check NAME is not empty
        
    if(strlen($NAME) < 2) {
            
    $errors['NAME'] = "Your name is not long enough";
        }  

        
    // Check TELEPHONE is not empty
        
    if (=== preg_match("/^((\(?0\d{4}\)?\s?\d{3}\s?\d{3})|(\(?0\d{3}\)?\s?\d{3}\s?\d{4})|(\(?0\d{2}\)?\s?\d{4}\s?\d{4}))(\s?\#(\d{4}|\d{3}))?$/"$_POST['TELEPHONE'])) {
            
    $errors['TELEPHONE'] = "Please enter valid phone number";
        }
        
        
    // Check EMAIL is valid
        
    if(strlen($EMAIL) < 5) {
            
    $errors['EMAIL'] = "Your email address is not long enough";
        } 

        
    // Check COMMENTS is valid
        
    if(strlen($COMMENTS) < 3) {
            
    $errors['COMMENTS'] = "Please enter a comment";
        } 

        
    // If no validation errors
        
    if (=== count($errors)) {

            
    // Sanitise details
            
    $NAME cleanInput($conn$_POST['NAME']);
            
    $TELEPHONE cleanInput($conn$_POST['TELEPHONE']);
            
    $EMAIL cleanInput(trim($conn$_POST['EMAIL']));
            
    $COMMENTS cleanInput($conn$_POST['COMMENTS']);

            
    // Insert user into the database
            
    $query "INSERT INTO 'test-form' 
                 ('DATE', 'NAME', 'TELEPHONE', 'EMAIL', 'COMMENTS')
                 VALUES
                 ('
    $DATE', '$NAME', '$TELEPHONE', '$EMAIL', '$COMMENTS')";

            
    $result mysqli_query($conn$query);

        if(
    mysql_errno() === 0){
          
    // Form submitted successfully
          
    header("Location: thankyou.php");

      } 
      }
     } 
     
     
     
    // Helpers
    function form_row_class($eName,$errors){
      return isset(
    $errors[$eName]) ? "form_error_row" "";  // Using isset to prevent undefined index
    }


    function 
    error_for($eName,$errors){
        return isset(
    $errors[$eName]) ? "<div class='form_error'>" .$errors[$eName] . "</div>" '';



    function 
    hsc($string){
      return 
    htmlspecialchars($string);
    }

    ?>


    <!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>Untitled Document</title>
    <link rel="stylesheet" type="text/css" href="styles.css" />
    </head>
    <body>
    <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
    <table class="form">
        <tr class="<?php echo form_row_class("NAME",$errors); ?>" >
          <th><label for="NAME">Name</label></th>
          <td><input name="NAME" id="NAME" type="text" value="<?php echo isset($_POST['NAME']) ? hsc($_POST['NAME']) : ''?>" />
            <?php echo error_for("NAME",$errors); ?></td>
        </tr>
        <tr class="<?php echo form_row_class("TELEPHONE",$errors); ?>">
          <th><label for="TELEPHONE">Telephone</label></th>
          <td><input name="TELEPHONE" id="TELEPHONE" type="text" value="<?php echo isset($_POST['TELEPHONE']) ? hsc($_POST['TELEPHONE']) : ''?>" />
            <?php echo error_for("TELEPHONE",$errors); ?></td>
        </tr>
        <tr class="<?php echo form_row_class("EMAIL",$errors); ?>">
          <th><label for="EMAIL">Email Address</label></th>
          <td><input name="EMAIL" id="EMAIL" type="text" "value="<?php echo isset($_POST['EMAIL']) ? hsc($_POST['EMAIL']) : ''?>" />
            <?php echo error_for("EMAIL",$errors); ?></td>
        </tr>
        <tr class="<?php echo form_row_class("COMMENTS",$errors); ?>">
          <th><label for="COMMENTS">Comments</label></th>
          <td><textarea name="COMMENTS" id="COMMENTS"><?php echo isset($_POST['COMMENTS']) ? hsc($_POST['COMMENTS']) : ''?></textarea>
            <?php echo error_for("COMMENTS",$errors); ?></td>
        </tr>
        <tr>
          <th></th>
          <td>
          <input type="submit" value="Go!" /></td>
        </tr>
      </table>
    </form>
    </body>
    </html>

    functions.php


    PHP Code:
    <?php

    require_once('db-connection.php');

    /**
     * Cleans input
     * @param String $data - the data to clean
     * @return String - the sanitised data
     */
    function cleanInput($data$conn){ // line 10
        
    if (get_magic_quotes_gpc()) {
            
    $data stripslashes($data);
            
    $data strip_tags($data);
            
    $data mysqli_real_escape_string($conn$data);
        } else {
            
    $data strip_tags($data); // line 16
            
    $data mysqli_real_escape_string($conn$data); // line 17
        
    }
        return 
    $data;
    }  

    ?>
    and db-connection.php

    PHP Code:
    <?php

    // setting variable for db connection
    $host "localhost";
    $username "root";
    $password "myPassword";
    $database "form";

    // connect to database
    $conn mysqli_connect("$host""$username""$password""$database");
    if (!
    $conn) {
        die(
    "Could not connect: " mysqli_error());
    }

    ?>

    The errors I'm getting are around the following. I've taken a screenshot of the errors and uploaded to here.

    I've put comments in my code such as " // line xx" so you know what the errros refer to. Thanks in advance

  2. #2
    Foozle Reducer ServerStorm's Avatar
    Join Date
    Feb 2005
    Location
    Burlington, Canada
    Posts
    2,699
    Mentioned
    89 Post(s)
    Tagged
    2 Thread(s)
    bytephp

    Hi you have defined the cleanInput() function with parameters in this order
    PHP Code:
    function cleanInput($data$conn
    However in your your form.php you call this function with the wrong parameter order id.
    PHP Code:
    $NAME cleanInput($conn$_POST['NAME']); 
    You need to call the cleanInput function like:
    PHP Code:
    $NAME cleanInput($_POST['NAME'], $conn); 
    All the errors you have shown relate to the incorrect or lack of an expected resource, but are trying to act on the wrong resource; therefore throwing the errors.

    Correct this and you should get your 'Thank you' message.

    Regards,
    Steve
    ictus==""

  3. #3
    SitePoint Member
    Join Date
    Feb 2012
    Posts
    24
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi Steve,

    Thanks for the help

    After making the amends I've come across a few more errors after submitting the form. I've tried doing a trim() on the EMAIL field which is causing an error along with a few others. Not sure how to go abouts fixing this, any ideas?

    Screenshot of errors here

    Once again ive put comments in my code such as " // line xx" where the error is.

    functions.php
    PHP Code:
    <?php

    require_once('db-connection.php');

    /**
     * Cleans input
     * @param String $data - the data to clean
     * @return String - the sanitised data
     */
    function cleanInput($data$conn){  // line 10
        
    if (get_magic_quotes_gpc()) {
            
    $data stripslashes($data);
            
    $data strip_tags($data);
            
    $data mysqli_real_escape_string($conn$data);
        } else {
            
    $data strip_tags($data);
            
    $data mysqli_real_escape_string($conn$data);  // line 17
        
    }
        return 
    $data;
    }  

    ?>
    form.php
    PHP Code:
    <?php

    require_once('db-connection.php');
    include(
    'functions.php');

    // date
    $DATE date(cleanInput("Y-m-d"$conn));

    $errors = array();

    // If request is a form submission
    if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    $NAME cleanInput($_POST['NAME'], $conn);  
    $EMAIL cleanInput($_POST['EMAIL'], $conn);  
    $COMMENTS cleanInput($_POST['COMMENTS'], $conn);  


    // Validation
    // Check NAME is not empty
        
    if(strlen($NAME) < 2) {
            
    $errors['NAME'] = "Your name is not long enough";
        }  

        
    // Check TELEPHONE is not empty
        
    if (=== preg_match("/^((\(?0\d{4}\)?\s?\d{3}\s?\d{3})|(\(?0\d{3}\)?\s?\d{3}\s?\d{4})|(\(?0\d{2}\)?\s?\d{4}\s?\d{4}))(\s?\#(\d{4}|\d{3}))?$/"$_POST['TELEPHONE'])) {
            
    $errors['TELEPHONE'] = "Please enter valid phone number";
        }
        
        
    // Check EMAIL is valid
        
    if(strlen($EMAIL) < 5) {
            
    $errors['EMAIL'] = "Your email address is not long enough";
        } 

        
    // Check COMMENTS is valid
        
    if(strlen($COMMENTS) < 3) {
            
    $errors['COMMENTS'] = "Please enter a comment";
        } 

        
    // If no validation errors
        
    if (=== count($errors)) {

            
    // Sanitise details
            
    $NAME cleanInput($_POST['NAME'], $conn);
            
    $TELEPHONE cleanInput($_POST['TELEPHONE'], $conn);
            
    $EMAIL cleanInput(trim($_POST['EMAIL'], $conn));   // line 46
            
    $COMMENTS cleanInput($_POST['COMMENTS'], $conn);

            
    // Insert user into the database
            
    $query "INSERT INTO 'test-form' 
                 ('DATE', 'NAME', 'TELEPHONE', 'EMAIL', 'COMMENTS')
                 VALUES
                 ('
    $DATE', '$NAME', '$TELEPHONE', '$EMAIL', '$COMMENTS')";

            
    $result mysqli_query($conn$query);

        if(
    mysql_errno() === 0){
          
    // Form submitted successfully
          
    header("Location: thankyou.php");

      } 
      }
     } 
     
     
     
    // Helpers
    function form_row_class($eName,$errors){
      return isset(
    $errors[$eName]) ? "form_error_row" "";  // Using isset to prevent undefined index
    }


    function 
    error_for($eName,$errors){
        return isset(
    $errors[$eName]) ? "<div class='form_error'>" .$errors[$eName] . "</div>" '';



    function 
    hsc($string){
      return 
    htmlspecialchars($string);
    }

    ?>


    <!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>Untitled Document</title>
    <link rel="stylesheet" type="text/css" href="styles.css" />
    </head>
    <body>
    <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
    <table class="form">
        <tr class="<?php echo form_row_class("NAME",$errors); ?>" >
          <th><label for="NAME">Name</label></th>
          <td><input name="NAME" id="NAME" type="text" value="<?php echo isset($_POST['NAME']) ? hsc($_POST['NAME']) : ''?>" />
            <?php echo error_for("NAME",$errors); ?></td>
        </tr>
        <tr class="<?php echo form_row_class("TELEPHONE",$errors); ?>">
          <th><label for="TELEPHONE">Telephone</label></th>
          <td><input name="TELEPHONE" id="TELEPHONE" type="text" value="<?php echo isset($_POST['TELEPHONE']) ? hsc($_POST['TELEPHONE']) : ''?>" />
            <?php echo error_for("TELEPHONE",$errors); ?></td>
        </tr>
        <tr class="<?php echo form_row_class("EMAIL",$errors); ?>">
          <th><label for="EMAIL">Email Address</label></th>
          <td><input name="EMAIL" id="EMAIL" type="text" "value="<?php echo isset($_POST['EMAIL']) ? hsc($_POST['EMAIL']) : ''?>" />
            <?php echo error_for("EMAIL",$errors); ?></td>
        </tr>
        <tr class="<?php echo form_row_class("COMMENTS",$errors); ?>">
          <th><label for="COMMENTS">Comments</label></th>
          <td><textarea name="COMMENTS" id="COMMENTS"><?php echo isset($_POST['COMMENTS']) ? hsc($_POST['COMMENTS']) : ''?></textarea>
            <?php echo error_for("COMMENTS",$errors); ?></td>
        </tr>
        <tr>
          <th></th>
          <td>
          <input type="submit" value="Go!" /></td>
        </tr>
      </table>
    </form>
    </body>
    </html>

  4. #4
    Foozle Reducer ServerStorm's Avatar
    Join Date
    Feb 2005
    Location
    Burlington, Canada
    Posts
    2,699
    Mentioned
    89 Post(s)
    Tagged
    2 Thread(s)
    Hi
    After a quick look, all the errors are related to an incorrect trim function bracket, it should be:
    PHP Code:
     $EMAIL cleanInput(trim($_POST['EMAIL']), $conn); 
    Steve
    ictus==""

  5. #5
    SitePoint Member
    Join Date
    Feb 2012
    Posts
    24
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by ServerStorm View Post
    Hi
    After a quick look, all the errors are related to an incorrect trim function bracket, it should be:
    PHP Code:
     $EMAIL cleanInput(trim($_POST['EMAIL']), $conn); 
    Steve
    Thanks Steve, sorted all the errors

    Sorry to keep asking, when one thing is fixed another arrises. My form doesnt seem to take you through to thankyou.php after sumbitting, it just stays on the same page. I realise in my form it is submitting to the same page, but I have set it to redirect to thankyou.php if no errors in the form are found. Snippets take from code below.

    PHP Code:
    // at top of form
    <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">


    // at bottom of my PHP after it has gone through the validation process.
        if(mysql_errno() === 0){
          // Form submitted successfully
          header("Location: thankyou.php");
    Another issues I've spotted, is my form no longer writes to the database. I've tried tracing steps back but can't seem to fix. Anyone spot why its not writing to my database?

  6. #6
    Foozle Reducer ServerStorm's Avatar
    Join Date
    Feb 2005
    Location
    Burlington, Canada
    Posts
    2,699
    Mentioned
    89 Post(s)
    Tagged
    2 Thread(s)
    Hi,

    You can't send headers after any output, say html like your <form> tag and other html has already outputted to a browser.

    You can either:
    • Branch the logic so you don't output anything to the browser before you redirect. This can get really sticky though because it is easy to miss spaces and so forth that do output to the browser... This approach would be like:
    PHP Code:
    <?php
    require_once('db-connection.php');
    include(
    'functions.php');
    // date
    $DATE date(cleanInput("Y-m-d"$conn));
    $errors = array();
    // If request is a form submission 
    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
     ...
      if(
    mysql_errno() === 0){ 
          
    // Form submitted successfully 
          
    header("Location: thankyou.php"); 

      }
    } else {
    // Edited this line to remove the bracket that shouldn't be there ?> 
    <!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>Untitled Document</title> 
    <link rel="stylesheet" type="text/css" href="styles.css" /> 
    </head> 
    <body> 
    <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
    ...
    <?php //close the if else ?>
    • Alernatively, and in my view better is to use output buffering like described here: http://stephan-gerlach.suite101.com/...-in-php-a26768 Searchin 'Output Buffering PHP' will yield lots of results for you to study and learn how you would need to adapt your scripts.
    Regards,
    Steve
    ictus==""

  7. #7
    SitePoint Member
    Join Date
    Feb 2012
    Posts
    24
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Yeah I tried the first one you mentioned but shows a "Parse error: syntax error, unexpected $end in C:\wamp\www\form6\form.php on line 131" which is end of my code.

  8. #8
    Foozle Reducer ServerStorm's Avatar
    Join Date
    Feb 2005
    Location
    Burlington, Canada
    Posts
    2,699
    Mentioned
    89 Post(s)
    Tagged
    2 Thread(s)
    Oh I just noticed that the if else bracket that I posted is being closed and then trying to close it again. I have edited it to have the proper closing bracket.
    ictus==""

  9. #9
    SitePoint Member
    Join Date
    Feb 2012
    Posts
    24
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by ServerStorm View Post
    Oh I just noticed that the if else bracket that I posted is being closed and then trying to close it again. I have edited it to have the proper closing bracket.
    Yeah I spotted that one and fixed it but gave the error I posted in my last post.

  10. #10
    Foozle Reducer ServerStorm's Avatar
    Join Date
    Feb 2005
    Location
    Burlington, Canada
    Posts
    2,699
    Mentioned
    89 Post(s)
    Tagged
    2 Thread(s)
    I just ran this and it works:
    PHP Code:
    // If request is a form submission
     if ($_SERVER['REQUEST_METHOD'] == 'POST'){  
       if(0 === 0){
           // Form submitted successfully
            header("Location: thankyou.php"); 
      }
    } else {?> 
    <!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>Untitled Document</title>
     <link rel="stylesheet" type="text/css" href="styles.css" />
     </head>
     <body>
     <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
      <input name='address' class='address_input' type="text" value="" />
      <a href='#'><input type="submit" name="test value="Test"></a>
    </form>
    <?php //close the if else ?>
    ictus==""

  11. #11
    SitePoint Member
    Join Date
    Feb 2012
    Posts
    24
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hmm.... ok try running my all the code which I've got and should show Parse error: syntax error, unexpected $end in C:\wamp\www\form7\form.php on line 124 which is the end of my code.

    form.php


    PHP Code:
    <?php

    require_once('db-connection.php');
    include(
    'functions.php');

     
    // Helpers
    function form_row_class($eName,$errors){
      return isset(
    $errors[$eName]) ? "form_error_row" "";  // Using isset to prevent undefined index
    }


    function 
    error_for($eName,$errors){
        return isset(
    $errors[$eName]) ? "<div class='form_error'>" .$errors[$eName] . "</div>" '';



    function 
    hsc($string){
      return 
    htmlspecialchars($string);
    }



    // date
    $DATE date(cleanInput("Y-m-d"$conn));

    $errors = array();

    // If request is a form submission
    if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    $NAME cleanInput($_POST['NAME'], $conn);  
    $EMAIL cleanInput($_POST['EMAIL'], $conn);  
    $COMMENTS cleanInput($_POST['COMMENTS'], $conn);  


    // Validation
    // Check NAME is not empty
        
    if(strlen($NAME) < 2) {
            
    $errors['NAME'] = "Your name is not long enough";
        }  

        
    // Check TELEPHONE is not empty
        
    if (=== preg_match("/^((\(?0\d{4}\)?\s?\d{3}\s?\d{3})|(\(?0\d{3}\)?\s?\d{3}\s?\d{4})|(\(?0\d{2}\)?\s?\d{4}\s?\d{4}))(\s?\#(\d{4}|\d{3}))?$/"$_POST['TELEPHONE'])) {
            
    $errors['TELEPHONE'] = "Please enter valid phone number";
        }
        
        
    // Check EMAIL is valid
        
    if(strlen($EMAIL) < 5) {
            
    $errors['EMAIL'] = "Your email address is not long enough";
        } 

        
    // Check COMMENTS is valid
        
    if(strlen($COMMENTS) < 3) {
            
    $errors['COMMENTS'] = "Please enter a comment";
        } 

        
    // If no validation errors
        
    if (=== count($errors)) {

            
    // Sanitise details
            
    $NAME cleanInput($_POST['NAME'], $conn);
            
    $TELEPHONE cleanInput($_POST['TELEPHONE'], $conn);
            
    $EMAIL cleanInput(trim($_POST['EMAIL']), $conn);  
            
    $COMMENTS cleanInput($_POST['COMMENTS'], $conn);

            
    // Insert user into the database
            
    $query "INSERT INTO 'test-form' 
                 ('DATE', 'NAME', 'TELEPHONE', 'EMAIL', 'COMMENTS')
                 VALUES
                 ('
    $DATE', '$NAME', '$TELEPHONE', '$EMAIL', '$COMMENTS')";

            
    $result mysqli_query($conn$query);

        if(
    mysql_errno() === 0){
          
    // Form submitted successfully
          
    header("Location: thankyou.php");

      } 
      } else {
      
    ?>


    <!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>Untitled Document</title>
    <link rel="stylesheet" type="text/css" href="styles.css" />
    </head>
    <body>
    <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
    <table class="form">
        <tr class="<?php echo form_row_class("NAME",$errors); ?>" >
          <th><label for="NAME">Name</label></th>
          <td><input name="NAME" id="NAME" type="text" value="<?php echo isset($_POST['NAME']) ? hsc($_POST['NAME']) : ''?>" />
            <?php echo error_for("NAME",$errors); ?></td>
        </tr>
        <tr class="<?php echo form_row_class("TELEPHONE",$errors); ?>">
          <th><label for="TELEPHONE">Telephone</label></th>
          <td><input name="TELEPHONE" id="TELEPHONE" type="text" value="<?php echo isset($_POST['TELEPHONE']) ? hsc($_POST['TELEPHONE']) : ''?>" />
            <?php echo error_for("TELEPHONE",$errors); ?></td>
        </tr>
        <tr class="<?php echo form_row_class("EMAIL",$errors); ?>">
          <th><label for="EMAIL">Email Address</label></th>
          <td><input name="EMAIL" id="EMAIL" type="text" "value="<?php echo isset($_POST['EMAIL']) ? hsc($_POST['EMAIL']) : ''?>" />
            <?php echo error_for("EMAIL",$errors); ?></td>
        </tr>
        <tr class="<?php echo form_row_class("COMMENTS",$errors); ?>">
          <th><label for="COMMENTS">Comments</label></th>
          <td><textarea name="COMMENTS" id="COMMENTS"><?php echo isset($_POST['COMMENTS']) ? hsc($_POST['COMMENTS']) : ''?></textarea>
            <?php echo error_for("COMMENTS",$errors); ?></td>
        </tr>
        <tr>
          <th></th>
          <td>
          <input type="submit" value="Go!" /></td>
        </tr>
      </table>
    </form>

    <?php ?>
    </body>
    </html>

    functions.php

    PHP Code:
    <?php

    require_once('db-connection.php');

    /**
     * Cleans input
     * @param String $data - the data to clean
     * @return String - the sanitised data
     */
    function cleanInput($data$conn){   
        if (
    get_magic_quotes_gpc()) {
            
    $data stripslashes($data);
            
    $data strip_tags($data);
            
    $data mysqli_real_escape_string($conn$data);
        } else {
            
    $data strip_tags($data);
            
    $data mysqli_real_escape_string($conn$data);
        }
        return 
    $data;


    ?>
    I also tried putting the <?php } ?> after the closing html tag but get the same output.

  12. #12
    Foozle Reducer ServerStorm's Avatar
    Join Date
    Feb 2005
    Location
    Burlington, Canada
    Posts
    2,699
    Mentioned
    89 Post(s)
    Tagged
    2 Thread(s)
    You are missing a } at line 78 I put "
    // MISSING THIS BRACKET'
    where it was missing. This if block should look like:
    PHP Code:
    // If no validation errors
    if (=== count($errors)) {

            
    // Sanitise details
            
    $NAME cleanInput($_POST['NAME'], $conn);
            
    $TELEPHONE cleanInput($_POST['TELEPHONE'], $conn);
            
    $EMAIL cleanInput(trim($_POST['EMAIL']), $conn);  
            
    $COMMENTS cleanInput($_POST['COMMENTS'], $conn);

            
    // Insert user into the database
            
    $query "INSERT INTO 'test-form' 
                 ('DATE', 'NAME', 'TELEPHONE', 'EMAIL', 'COMMENTS')
                 VALUES
                 ('
    $DATE', '$NAME', '$TELEPHONE', '$EMAIL', '$COMMENTS')";

            
    $result mysqli_query($conn$query);

        if(
    mysql_errno() === 0){
          
    // Form submitted successfully
          
    header("Location: thankyou.php");

        } 
      } 
    // MISSING THIS BRACKET
    } else { 
    As I did not want to create a database that matched yours I could not test that part but I do know that I make it to the thank you page if I comment out and fake return proper database results.

    If I can recommend one thing to you is that you need to either check that your brackets both curly and elipitical are closed properly, this was the third error caused by malformed brackets. If your editor doesn't auto highlight the matching bracket then spacing your code and ensuring that the brackets line up over such big if else statements will help. I would recommend that you work with an IDE that helps you make sure the brackets belong together.

    One free IDE that is powerful is Eclipse and PDT; you can search on this.

    Hope you are on you way now.

    Steve
    ictus==""

  13. #13
    SitePoint Member
    Join Date
    Feb 2012
    Posts
    24
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks Steve

    Yeah good idea, the text editor I use does not highlight closing closing braces, brackets etc so I've now switched to NetBeans IDE as it has a lot of documentation on it for PHP.

    Unfortunatly this is still not writing to my database, plus it does not take me through to the thankyou.php page, I just get a blank form.php page (without the form there. Futhermore, it is skipping out the validation. Grr! Sorry to keep asking for help, but any idea how to fix?

    form.php
    PHP Code:
    <?php

    require_once('db-connection.php');
    include(
    'functions.php');


     
    // Helpers
    function form_row_class($eName,$errors){
      return isset(
    $errors[$eName]) ? "form_error_row" "";  // Using isset to prevent undefined index
    }


    function 
    error_for($eName,$errors){
        return isset(
    $errors[$eName]) ? "<div class='form_error'>" .$errors[$eName] . "</div>" '';



    function 
    hsc($string){
      return 
    htmlspecialchars($string);
    }



    // date
    $DATE date(cleanInput("Y-m-d"$conn));

    $errors = array();

    // If request is a form submission
    if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    $NAME cleanInput($_POST['NAME'], $conn);  
    $EMAIL cleanInput($_POST['EMAIL'], $conn);  
    $COMMENTS cleanInput($_POST['COMMENTS'], $conn);  


    // Validation
    // Check NAME is not empty
        
    if(strlen($NAME) < 2) {
            
    $errors['NAME'] = "Your name is not long enough";
        }  

        
    // Check TELEPHONE is not empty
        
    if (=== preg_match("/^((\(?0\d{4}\)?\s?\d{3}\s?\d{3})|(\(?0\d{3}\)?\s?\d{3}\s?\d{4})|(\(?0\d{2}\)?\s?\d{4}\s?\d{4}))(\s?\#(\d{4}|\d{3}))?$/"$_POST['TELEPHONE'])) {
            
    $errors['TELEPHONE'] = "Please enter valid phone number";
        }
        
        
    // Check EMAIL is valid
        
    if(strlen($EMAIL) < 5) {
            
    $errors['EMAIL'] = "Your email address is not long enough";
        } 

        
    // Check COMMENTS is valid
        
    if(strlen($COMMENTS) < 3) {
            
    $errors['COMMENTS'] = "Please enter a comment";
        } 

        
    // If no validation errors
        
    if (=== count($errors)) {

            
    // Sanitise details
            
    $NAME cleanInput($_POST['NAME'], $conn);
            
    $TELEPHONE cleanInput($_POST['TELEPHONE'], $conn);
            
    $EMAIL cleanInput(trim($_POST['EMAIL']), $conn);  
            
    $COMMENTS cleanInput($_POST['COMMENTS'], $conn);

            
    // Insert user into the database
            
    $query "INSERT INTO 'test-form' 
                 ('DATE', 'NAME', 'TELEPHONE', 'EMAIL', 'COMMENTS')
                 VALUES
                 ('
    $DATE', '$NAME', '$TELEPHONE', '$EMAIL', '$COMMENTS')";

            
    $result mysqli_query($conn$query);

        if(
    mysqli_errno($conn) === 0){
          
    // Form submitted successfully
          
    header("Location: thankyou.php");
        exit;
        } 
      }
      } else {
       echo 
    "Sorry, your comment could not be saved at this time";

      
    //  DEBUGGING ONLY - DISABLE IN PRODUCTION SITE
      
    echo "<p> MySQLi Error: " mysqli_error($conn);"</p>"

    ?>


    <!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>Untitled Document</title>
    <link rel="stylesheet" type="text/css" href="styles.css" />
    </head>
    <body>
    <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
    <table class="form">
        <tr class="<?php echo form_row_class("NAME",$errors); ?>" >
          <th><label for="NAME">Name</label></th>
          <td><input name="NAME" id="NAME" type="text" value="<?php echo isset($_POST['NAME']) ? hsc($_POST['NAME']) : ''?>" />
            <?php echo error_for("NAME",$errors); ?></td>
        </tr>
        <tr class="<?php echo form_row_class("TELEPHONE",$errors); ?>">
          <th><label for="TELEPHONE">Telephone</label></th>
          <td><input name="TELEPHONE" id="TELEPHONE" type="text" value="<?php echo isset($_POST['TELEPHONE']) ? hsc($_POST['TELEPHONE']) : ''?>" />
            <?php echo error_for("TELEPHONE",$errors); ?></td>
        </tr>
        <tr class="<?php echo form_row_class("EMAIL",$errors); ?>">
          <th><label for="EMAIL">Email Address</label></th>
          <td><input name="EMAIL" id="EMAIL" type="text" "value="<?php echo isset($_POST['EMAIL']) ? hsc($_POST['EMAIL']) : ''?>" />
            <?php echo error_for("EMAIL",$errors); ?></td>
        </tr>
        <tr class="<?php echo form_row_class("COMMENTS",$errors); ?>">
          <th><label for="COMMENTS">Comments</label></th>
          <td><textarea name="COMMENTS" id="COMMENTS"><?php echo isset($_POST['COMMENTS']) ? hsc($_POST['COMMENTS']) : ''?></textarea>
            <?php echo error_for("COMMENTS",$errors); ?></td>
        </tr>
        <tr>
          <th></th>
          <td>
          <input type="submit" value="Go!" /></td>
        </tr>
      </table>
    </form>
    </body>
    </html>
    <?php ?>
    functions.php
    PHP Code:
    <?php

    require_once('db-connection.php');

    /**
     * Cleans input
     * @param String $data - the data to clean
     * @return String - the sanitised data
     */
    function cleanInput($data$conn){   
        if (
    get_magic_quotes_gpc()) {
            
    $data stripslashes($data);
            
    $data strip_tags($data);
            
    $data mysqli_real_escape_string($conn$data);
        } else {
            
    $data strip_tags($data);
            
    $data mysqli_real_escape_string($conn$data);
        }
        return 
    $data;


    ?>

  14. #14
    SitePoint Member
    Join Date
    Feb 2012
    Posts
    24
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Sorry fixed the error in my last post. Now it appears still not to write to the database not go to the thankyou page.

    form.php
    PHP Code:
    <?php

    require_once('db-connection.php');
    include(
    'functions.php');


     
    // Helpers
    function form_row_class($eName,$errors){
      return isset(
    $errors[$eName]) ? "form_error_row" "";  // Using isset to prevent undefined index
    }


    function 
    error_for($eName,$errors){
        return isset(
    $errors[$eName]) ? "<div class='form_error'>" .$errors[$eName] . "</div>" '';



    function 
    hsc($string){
      return 
    htmlspecialchars($string);
    }



    // date
    $DATE date(cleanInput("Y-m-d"$conn));

    $errors = array();

    // If request is a form submission
    if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    $NAME cleanInput($_POST['NAME'], $conn);  
    $EMAIL cleanInput($_POST['EMAIL'], $conn);  
    $COMMENTS cleanInput($_POST['COMMENTS'], $conn);  


    // Validation
    // Check NAME is not empty
        
    if(strlen($NAME) < 2) {
            
    $errors['NAME'] = "Your name is not long enough";
        }  

        
    // Check TELEPHONE is not empty
        
    if (=== preg_match("/^((\(?0\d{4}\)?\s?\d{3}\s?\d{3})|(\(?0\d{3}\)?\s?\d{3}\s?\d{4})|(\(?0\d{2}\)?\s?\d{4}\s?\d{4}))(\s?\#(\d{4}|\d{3}))?$/"$_POST['TELEPHONE'])) {
            
    $errors['TELEPHONE'] = "Please enter valid phone number";
        }
        
        
    // Check EMAIL is valid
        
    if(strlen($EMAIL) < 5) {
            
    $errors['EMAIL'] = "Your email address is not long enough";
        } 

        
    // Check COMMENTS is valid
        
    if(strlen($COMMENTS) < 3) {
            
    $errors['COMMENTS'] = "Please enter a comment";
        } 

        
    // If no validation errors
        
    if (=== count($errors)) {

            
    // Sanitise details
            
    $NAME cleanInput($_POST['NAME'], $conn);
            
    $TELEPHONE cleanInput($_POST['TELEPHONE'], $conn);
            
    $EMAIL cleanInput(trim($_POST['EMAIL']), $conn);  
            
    $COMMENTS cleanInput($_POST['COMMENTS'], $conn);

            
    // Insert user into the database
            
    $query "INSERT INTO 'test-form' 
                 ('DATE', 'NAME', 'TELEPHONE', 'EMAIL', 'COMMENTS')
                 VALUES
                 ('
    $DATE', '$NAME', '$TELEPHONE', '$EMAIL', '$COMMENTS')";

            
    $result mysqli_query($conn$query);

        if(
    mysqli_errno($conn) === 0){
          
    // Form submitted successfully
          
    header("Location: thankyou.php");
        exit;
        } 
      }
      } else {
       echo 
    "Sorry, your comment could not be saved at this time";

      
    //  DEBUGGING ONLY - DISABLE IN PRODUCTION SITE
      
    echo "<br/><br /> MySQLi Error: " mysqli_error($conn);
      }
    ?>


    <!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>Untitled Document</title>
    <link rel="stylesheet" type="text/css" href="styles.css" />
    </head>
    <body>
    <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
    <table class="form">
        <tr class="<?php echo form_row_class("NAME",$errors); ?>" >
          <th><label for="NAME">Name</label></th>
          <td><input name="NAME" id="NAME" type="text" value="<?php echo isset($_POST['NAME']) ? hsc($_POST['NAME']) : ''?>" />
            <?php echo error_for("NAME",$errors); ?></td>
        </tr>
        <tr class="<?php echo form_row_class("TELEPHONE",$errors); ?>">
          <th><label for="TELEPHONE">Telephone</label></th>
          <td><input name="TELEPHONE" id="TELEPHONE" type="text" value="<?php echo isset($_POST['TELEPHONE']) ? hsc($_POST['TELEPHONE']) : ''?>" />
            <?php echo error_for("TELEPHONE",$errors); ?></td>
        </tr>
        <tr class="<?php echo form_row_class("EMAIL",$errors); ?>">
          <th><label for="EMAIL">Email Address</label></th>
          <td><input name="EMAIL" id="EMAIL" type="text" "value="<?php echo isset($_POST['EMAIL']) ? hsc($_POST['EMAIL']) : ''?>" />
            <?php echo error_for("EMAIL",$errors); ?></td>
        </tr>
        <tr class="<?php echo form_row_class("COMMENTS",$errors); ?>">
          <th><label for="COMMENTS">Comments</label></th>
          <td><textarea name="COMMENTS" id="COMMENTS"><?php echo isset($_POST['COMMENTS']) ? hsc($_POST['COMMENTS']) : ''?></textarea>
            <?php echo error_for("COMMENTS",$errors); ?></td>
        </tr>
        <tr>
          <th></th>
          <td>
          <input type="submit" value="Go!" /></td>
        </tr>
      </table>
    </form>
    </body>
    </html>

  15. #15
    dooby dooby doo silver trophybronze trophy
    spikeZ's Avatar
    Join Date
    Aug 2004
    Location
    Manchester UK
    Posts
    13,788
    Mentioned
    151 Post(s)
    Tagged
    3 Thread(s)
    Hi, it's likely that your query is failing then meaning the mysqli_errno wouldn't be 0 - you haven't written in an error handler or what to do if it isnt yet!
    So to that end, have a look at your query line.

    Try:
    Code:
    // Insert user into the database 
    $query = "
        INSERT INTO
            test-form  (
                DATE
              , NAME
              , TELEPHONE
              , EMAIL
              , COMMENTS
        ) VALUES (
                '$DATE'
              , '$NAME'
              , '$TELEPHONE'
              , '$EMAIL'
              , '$COMMENTS'
              )";
    See what happens
    Mike Swiffin - Community Team Advisor
    Only a woman can read between the lines of a one word answer.....

  16. #16
    SitePoint Member
    Join Date
    Feb 2012
    Posts
    24
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by spikeZ View Post
    Hi, it's likely that your query is failing then meaning the mysqli_errno wouldn't be 0 - you haven't written in an error handler or what to do if it isnt yet!
    So to that end, have a look at your query line.

    Try:
    Code:
    // Insert user into the database 
    $query = "
        INSERT INTO
            test-form  (
                DATE
              , NAME
              , TELEPHONE
              , EMAIL
              , COMMENTS
        ) VALUES (
                '$DATE'
              , '$NAME'
              , '$TELEPHONE'
              , '$EMAIL'
              , '$COMMENTS'
              )";
    See what happens
    Hi SpikeZ,

    Thanks for your reply. Ummm, sorry but a bit unsure of what to do? I've checked through the insert statement and looks ok to me.


  17. #17
    dooby dooby doo silver trophybronze trophy
    spikeZ's Avatar
    Join Date
    Aug 2004
    Location
    Manchester UK
    Posts
    13,788
    Mentioned
    151 Post(s)
    Tagged
    3 Thread(s)
    I have removed all the single quotes from the table name and field names.
    Mike Swiffin - Community Team Advisor
    Only a woman can read between the lines of a one word answer.....

  18. #18
    SitePoint Member
    Join Date
    Feb 2012
    Posts
    24
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by spikeZ View Post
    I have removed all the single quotes from the table name and field names.
    Haha doh! Ok have tried that but unfortunatly just does the same thing as it was doing before.

  19. #19
    dooby dooby doo silver trophybronze trophy
    spikeZ's Avatar
    Join Date
    Aug 2004
    Location
    Manchester UK
    Posts
    13,788
    Mentioned
    151 Post(s)
    Tagged
    3 Thread(s)
    ok so you need to take your debugging up a notch.

    See if the query returns an error message and print out the query to see if everything is set up ok.
    Change your result line to:
    PHP Code:
     $result mysqli_query($conn$query) or die(mysqli_error(). $query); 
    Mike Swiffin - Community Team Advisor
    Only a woman can read between the lines of a one word answer.....

  20. #20
    SitePoint Member
    Join Date
    Feb 2012
    Posts
    24
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Yeah that returns the following error message - see screenshot of error

    That refers to this line $result = mysqli_query($conn, $query) or die(mysqli_error(). $query);

    Ive put the code into NetBeans IDE and its saying $result appears to be unused in its scope. Dont know if that has to do with anything? Plus its saying the line below if(mysqli_errno($conn) === 0){ the variable $conn is uninitialized. Dont know if that means anything either.

    Thanks for your help with this

  21. #21
    SitePoint Member
    Join Date
    Feb 2012
    Posts
    24
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Edit: found the issue. Table name was called "test-form" which I didnt know this untill I saw the error displayed but it doesnt like hyphens in database names.

    Thanks SpikeZ, adding the debugging in helped find the error! Cheers for your help!

  22. #22
    dooby dooby doo silver trophybronze trophy
    spikeZ's Avatar
    Join Date
    Aug 2004
    Location
    Manchester UK
    Posts
    13,788
    Mentioned
    151 Post(s)
    Tagged
    3 Thread(s)
    You are most welcome.
    The thing with the $conn variable, once it has been initialised you dont really need to call it at each time it is being used. So after the connection has been made you can pretty much ignore it.
    Mike Swiffin - Community Team Advisor
    Only a woman can read between the lines of a one word answer.....

  23. #23
    SitePoint Member
    Join Date
    Feb 2012
    Posts
    24
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Ok cool thanks

    Just two quick question. When for form page first loads it displays all of the words from the else part of the following statement. I can remove it leaving the else statment blank, however would be nice to display the error if the database goes down or whatever. How can this be done?

    PHP Code:
            $result mysqli_query($conn$query) or die(mysqli_error($conn) . $query);

            if (
    $result != FALSE) {
                
    // Form submitted successfully
                
    header("Location: thankyou.php");
                exit;
            }
        }
    } else {
        echo 
    "Sorry, your comment could not be saved at this time";

        
    //  DEBUGGING ONLY - DISABLE IN PRODUCTION SITE
        
    echo "<br/><br /> MySQLi Error: " mysqli_error($conn);

    Also what collation do you have set for each row in the database? phpMyAdmin defaults to latin1_Swedish_ci, should it change to latin1_generic_ci or utf8mb4_unicode_ci?

  24. #24
    dooby dooby doo silver trophybronze trophy
    spikeZ's Avatar
    Join Date
    Aug 2004
    Location
    Manchester UK
    Posts
    13,788
    Mentioned
    151 Post(s)
    Tagged
    3 Thread(s)
    You need to move the comments up into the PREVIOUS else.
    What the code says at the minute is:

    if the form has been sent
    -- process it
    -- insert into the database
    -- redirect
    otherwise
    --display the message...

    So you would end up with:

    Code PHP:
     
          header("Location: thankyou.php"); 
        exit; 
        }  
      } else { 
        echo "Sorry, your comment could not be saved at this time"; 
     
       //  DEBUGGING ONLY - DISABLE IN PRODUCTION SITE 
       echo "<br/><br /> MySQLi Error: " . mysqli_error($conn); 
       } 
      } // <-- closes the if(SERVER METHOD) line
    I generally use latin1_Swedish_ci because it is the default setting and has generally worked for me. I'm sure if you ask over in the MySQL forum then you would get a much more comprehensive answer!!
    Mike Swiffin - Community Team Advisor
    Only a woman can read between the lines of a one word answer.....

  25. #25
    SitePoint Member
    Join Date
    Feb 2012
    Posts
    24
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Ah ok, makes sense. Thanks once again for your help!


Bookmarks

Posting Permissions

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