Validate form and insert into Database with PHP

Asked

Viewed 1,053 times

3

Hello

I’m still a beginner in PHP and stagnated validating the contact form of my site.

Complete client-side validation using Javascript, but on the server-side you still haven’t completed the task, so ask for your help.

I have the HTML form below:

<form id="form" name="contactForm" method="post" action="php/Form.php">
            <div>
                <label for="name">Your name</label> 
                <input type="text" id="name" name="name" maxlength="40" placeholder="Write your Name"   >
                <span class="error"><?php echo $nameError;  ?></span>
            </div>
            <div>
                <label for="email">Your email</label>
                <input type="email" id="email" name="user_mail" placeholder="[email protected]">
                <span class="error"><?php echo $emailError;  ?></span> 
            </div>                
            <div>
                <label for="topic">Select Topic</label>
                <select id="topic" name="topic">
                    <option selected disabled hidden value="">Choose a Topic</option>
                    <option value="link">Site Link</option>
                    <option value="copyright">Copyright</option>
                    <option value="errors">Site/Article errors</option>
                    <option value="feedback">Feedback</option>
                    <option value="other">Other</option>
                </select>
                <span class="error"><?php echo $topicError;  ?></span>
            </div>                
            <div>
                <label for="msg">Your message</label>
                <textarea id="msg" name="user_message" placeholder="Write your message"></textarea>
                <span class="error"><?php echo $msgError;  ?></span>
            </div>                
            <div class="button">
                <button type="submit" id="submit" name="submit"  value="true">Submit</button> 
                <span class="success"></span>
            </div>
        </form>

And in formuly_contacts.php I wrote the following code:

$servername = "localhost:3306";
$username = "root";
$password = "";
$dbname = "site_comboios";


$name = $_POST['name'];
$email = $_POST['user_mail'];
$topic = $_POST['topic'];
$msg = $_POST['user_message'];


if( isset( $_POST['submit'])) {
if(empty( $name) || isset($name) ) {
    $nameError = "Name is required" ;
}

if(empty( $email) || isset($email)) {
    $emailError = "Email is required";
} elseif(filter_var($email,FILTER_VALIDATE_EMAIL)) {
  $emailError = "Please insert a correct email address";  
}  

if(empty( $topic) || isset($topic) ) {
    $topicError = "Please choose a topic";
} 

if(empty( $msg) || isset($msg) ) {
    $msgError = "Let us know your opinion";
}
}

//Create connection to database
$mysqli = new mysqli($servername, $username, $password, $dbname);

//check connection
if($mysqli->connect_errno) {
echo 'Error connecting to database';
}

//Prepared Statement
$stmt = $mysqli->prepare("INSERT INTO contacts(Nome, Email, Topico,  Mensagem)  VALUES(?, ?, ?, ?)" );
$stmt->bind_param('ssss', $name, $email, $topic, $msg);
$stmt->execute();

What happens when you press the "Submit" button is it is submitted even without any data entered! (this test is always done with Javascript turned off, of course)

No validation and a new record is always created in the database.

What I’m doing wrong in the validation part?

Thanks for the help

1 answer

0

Analyzing your code, it is visible the lack of validation of when a new record should be inserted or not.

You see, you validate input to input. But it does not validate whether or not it should be inserted, it just inserts.

Based on its validation, the fastest solution would be to replace the error variables with an array (it is easier to validate).

$errorList = [];

if(empty($_POST['user_mail'])) {
    $errorList["emailError"] = "Email is required";
} else {
    $email = test_input($_POST['user_mail']);
}

And validate if there are error messages:

if (count($errorList) == 0) {
    $sql = "INSERT INTO formulario_contactos (Nome, Email, Topico, Mensagem)
    VALUES ('$name', '$email' , '$topic' , '$mensagem')";

    if ($conn->query($sql) === TRUE) {
        echo 'Your message has been successfully sent';
    } else {
        echo 'Error'. $sql . $conn->error;    
    }
} 
else 
{
    /** tratamento de erros **/
}

This would solve the validation problem when submitting your form. However, your code does not only have this problem. The first is that it is vulnerable. The function mysqli_real_escape_string not to protect your code, just to escape some characters, use Prepared statements in place. You can read more about SQL Injection in the link below. There is a topic about mysqli_real_escape_string. https://phpdelusions.net/sql_injection

Performing the above mentioned procedure, the function test_input becomes useless. Except for trim that can be used in some cases that really can not occur extra spaces.

The sanitization you are performing is intended for display, nothing else. It is not a safety, therefore, beyond prepared statements, there is no further need for your code. Sanitizations for display should be performed at the time of display and not at insertion.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.