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

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 (0 === 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 (0 === 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

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

// 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 :slight_smile:

bytephp

Hi you have defined the cleanInput() function with parameters in this order

function cleanInput($data, $conn)

However in your your form.php you call this function with the wrong parameter order id.


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

You need to call the cleanInput function like:


$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

Hi Steve,

Thanks for the help :slight_smile:

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

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

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 (0 === 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 (0 === 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>

Hi
After a quick look, all the errors are related to an incorrect trim function bracket, it should be:


 $EMAIL = cleanInput(trim($_POST['EMAIL']), $conn);

Steve

Thanks Steve, sorted all the errors :smiley:

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.


// 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?

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
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 ?>
 

[LIST]
[*]Alernatively, and in my view better is to use output buffering like described here: http://stephan-gerlach.suite101.com/output-buffer-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.
[/LIST]Regards,
Steve

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.

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.

I just ran this and it works:


// 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 ?>

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

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 (0 === 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 (0 === 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

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.

You are missing a } at line 78 I put "[LEFT]// MISSING THIS BRACKET’ [/LEFT]where it was missing[LEFT] [/LEFT]. This if block should look like:


// If no validation errors
if (0 === 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

Thanks Steve :slight_smile:

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

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 (0 === 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 (0 === 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

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;
}

?>

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

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 (0 === 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 (0 === 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>

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:


// 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.


I have removed all the single quotes from the table name and field names. :slight_smile:

Haha doh! Ok have tried that but unfortunatly just does the same thing as it was doing before.

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:


 $result = mysqli_query($conn, $query) or die(mysqli_error(). $query); 

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 :slight_smile: