Validation not working

I have not idea what is wrong, i got an example from a site and made the changes here’s my code so far:
(connecting to the database works and submits data, but i can’t get the validation to work)
validation.php

<?php
// define variables and set to empty values
$u_nameError = $u_emailError = "";
$u_name = $u_email = $message = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  if (empty($_POST["u_name"])) {
    $u_nameError = "Name is required";
  } else {
    $u_name = test_input($_POST["u_name"]);
    // check if u_name only contains letters and whitespace
    if (!preg_match("/^[a-zA-Z ]*$/",$u_name)) {
      $u_nameError = "Only letters and white space allowed";
    }
  }

  if (empty($_POST["u_email"])) {
    $u_emailError = "Email is required";
  } else {
    $u_email = test_input($_POST["u_email"]);
    // check if e-mail address is well-formed
    if (!filter_var($u_email, FILTER_VALIDATE_EMAIL)) {
      $u_emailError = "Invalid email format";
    }
  }

  if (empty($_POST["message"])) {
    $message = "";
  } else {
    $message = test_input($_POST["message"]);
  }

}

function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}
?>

thankyou.php

<?php
error_reporting(E_ALL);
ini_set('display_errors', 'true'); 
require 'connection.php';
require 'validation.php';
$conn = Connect();

/* skip testing for the POST array for now */

/* Prepare an insert statement */
$query = "INSERT INTO tb_cform (u_name, u_email, subj, message) VALUES (?,?,?,?)";
$stmt = $conn->prepare($query);

$stmt->bind_param("ssss", $_POST['u_name'], $_POST['u_email'], $_POST['subj'], $_POST['message']);

/* Execute the statement */
$stmt->execute();

if ($stmt->affected_rows > 0) {
  echo "Thank You For Contacting Us <br>";
  printf("rows inserted: %d\n", $stmt->affected_rows);
} else {
  echo "Did not enter data";
}

/* close statement */
$stmt->close();

$conn->close();
?>

connection.php

<?php
error_reporting(E_ALL);
ini_set('display_errors', 'true'); 
 
function Connect()
{
 $dbhost = "localhost";
 $dbuser = "root";
 $dbpass = "";
 $dbname = "responses";
 
 // Create connection
 $conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname) or die($conn->connect_error);
 
 return $conn;
}
 
?>

You seem to be setting $u_emailError and $u_nameError but I don’t see where you are printing them out if they are not empty…

index.php:

<form action="thankyou.php" method="post">
        <label>Name:</label><br>
        <input type="text" name="u_name" required><br>
        <span class="error"><?php echo $u_nameError;?></span><br><br>    
        <label>Email:</label><br>
        <input type="email" name="u_email" required><br>
        <span class="error"><?php echo $u_emailError;?></span><br><br>
        <label>Subject:</label><br>
        <input type="text" name="subj" required><br>
        <label>Message:</label><br>
        <textarea name="message" required></textarea><br>
        <input type="submit" value="Submit"><br>
</form>

Okay, but where is your logic that takes you back to index.php if there is an error?

I don’t know i tried emulating the example from: https://www.formget.com/php-contact-form/

If you don’t understand the logic it might be better to copy the script verbatim and get that working first. Only then try to incorporate it into the code you already have.

Is there any easier way just using javascript in the index.php file?

Js validation can’t be relied upon.
I can see a few things wrong in the code, but too busy just now.

1 Like

I’m finding this very stressfull every example i’ve come that suppose to work is not working for me, I’ve changed the variables and various so called solutions. But I’m getting no where.

Which is why getting the original to work first and then changing it would make more sense.

Well i’ve scrapped the validation.php code and started again. So with form going to thankyou.php how do i code a validation with only u_name to make things simple.

I don’t see that only validating one field is going to simplify things at all when there appears to be an error in the logic flow.

1 Like

Take it one step at a time.

As I posted in your other topic, unless they are “anything goes” - which is rarely the case - you need to do some critical thinking regarding the input values

If you can describe what an input value needs to be in the form of a sentence then “translating” to code will not be that difficult.

As a contrived example

Must have a minimum of three characters and a maximum of ten characters.
Only numeric characters, spaces and dashes are allowed.
A space can not be adjacent to another space or a dash
If there are dashes, there must be a minimum of two digits and a maximum of four digits between and outside of the dashes.

etc.

But that’s the problem I don’t know how to code it and i don’t know where to place it. All attempts so far have failed.

This is literally my attempt in index.php:

<?php
$name_error = '';
        if(isset($_POST['submit'])){
                $name = $_POST['u_name'];

        if(empty($name)){
                $name_error = 'Please enter your name';
        }
}
?>
<form action="thankyou.php" method="post">
        <label for="u_name">Name:</label><br>
        <input type="text" name="u_name" id="u_name" ><br>
        <?php echo $name_error; ?></br>
        <label for="u_email">Email:</label><br>
        <input type="email" name="u_email" id="u_email" ><br>
        <?php echo $email_error; ?></br>
        <label for="subj">Subject:</label><br>
        <input type="text" name="subj" id="subj"><br>
        <?php echo $subj_error; ?></br>
        <label for="message">Message:</label><br>
        <textarea name="message" id="message"></textarea><br>
        <?php echo $message_error; ?></br>
        <input type="submit" name="submit" value="Submit"><br>

</form>

This is my current attempt at validation after adapting multiple tutorials into my code but getting no where.

You don’t need to worry about how to write the code for any validation yet. The first step is deciding what is OK and what is not OK

So far, the only thing you are checking is that name isn’t empty, so all of these would pass, and I’m sure they all wouldn’t be OK names to you.

a
6
g8Dl*v$R6
oneexceptionlylongunbrokenstringoftextthatgoesonandonadonindefifinately
<script>alert('got ya!');</script>
" OR 1 = 1; DROP DATABASE;

Note, using prepared statements will do a lot, but not everything.

No, they wouldn’t.

Perhaps you would like to demonstrate to us how effective your design logic is because so far, I only see legacy logic which is if(isset($_POST['submit'])). This is an amateur hack that most new PHP users use.

No, I know it’s bad and I know what is acceptable as input, all i want to know is where should i put the validation code in either: index.php, thankyou.php, connection.php (unlikely) or create a new file like validation.php. Also any links to any recent php validation that works and is best adaptable to my current code.