Pass error variables between two php files

3

Hello

I'm trying to validate a form in different files, but I can not pass the error messages between them.

In index.php I have the form code:

<!DOCTYPE html>

    <html>
    <head>
    <title>Great Train Journeys</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-    scale=1.0">
    <link rel="stylesheet" href="css/style.css">
    <script src="js/jquery-3.1.0.min.js" type="text/javascript"></script>
    <script src="js/scripts.js" type="text/javascript"></script>
    </head>
    <body>

    <div id="container">
        <ul class="nav">
            <li><a href="index.php">home</a></li> 

            <li>
                <a href="#">destinations</a>
                <div>    
                <div class="nav-column">                        
                    <h3>uk & ireland</h3>

                    <ul>
                        <li> <a href="#">England</a> </li>
                        <li> <a href="#">Ireland</a> </li>
                        <li> <a href="#">Scotland</a> </li>
                        <li> <a href="#">Wales</a> </li>
                    </ul>


                    <h3>mainland europe</h3>
                    <ul>
                        <li> <a href="#">Austria</a> </li>
                        <li> <a href="#">Belgium</a> </li>
                        <li> <a href="#">Bosnia & Herzegovina</a> </li>
                        <li> <a href="#">Bulgaria</a> </li>
                        <li> <a href="#">Croatia</a> </li>
                        <li> <a href="#">Czech Republic</a> </li>
                        <li> <a href="#">Denmark</a> </li>
                        <li> <a href="#">Estonia</a> </li>
                        <li> <a href="#">Finland</a> </li>
                        <li> <a href="#">France</a> </li>
                        <li> <a href="#">Germany</a> </li>
                        <li> <a href="#">Greece</a> </li>
                        <li> <a href="#">Hungary</a> </li>
                        <li> <a href="#">Italy</a> </li>
                        <li> <a href="#">Latvia</a> </li>
                        <li> <a href="#">Lithuania</a> </li>
                        <li> <a href="#">Luxembourg</a> </li>
                    </ul>
                </div>

                <div class="nav-column">
                    <h3>mainland europe cont...</h3>
                    <ul>                                                                                                               
                        <li> <a href="#">Macedonia</a> </li>
                        <li> <a href="#">Montenegro</a> </li>
                        <li> <a href="#">Norway</a> </li>
                        <li> <a href="#">Poland</a> </li>
                        <li> <a href="#">Portugal</a> </li>
                        <li> <a href="#">Roménia</a> </li>
                        <li> <a href="#">Russia</a> </li>
                        <li> <a href="#">Serbia</a> </li>
                        <li> <a href="#">Slovakia</a> </li>
                        <li> <a href="#">Slovenia</a> </li>
                        <li> <a href="#">Spain</a> </li>
                        <li> <a href="#">Sweden</a> </li>
                        <li> <a href="#">Switzerland</a> </li>
                        <li> <a href="#">The Netherlands</a> </li>
                        <li> <a href="#">Turkey</a> </li>
                        <li> <a href="#">Ukraine</a> </li>
                    </ul>
                </div>

                     <div class="nav-column">
                    <h3>north america</h3>
                    <ul>
                        <li> <a href="#">Alaska</a> </li>
                        <li> <a href="#">Canada</a> </li>
                        <li> <a href="#">Mexico</a> </li>
                        <li> <a href="#">United States</a> </li>
                    </ul>                     

                    <h3>central america</h3>
                    <ul>
                        <li> <a href="#">Guatemala</a> </li>
                        <li> <a href="#">Costa Rica</a> </li>
                        <li> <a href="#">Cuba</a> </li>
                        <li> <a href="#">Panama</a> </li>
                        <li> <a href="#">St Kitts and Nevis</a> </li>
                    </ul>                 

                    <h3>south america</h3>
                    <ul>
                        <li> <a href="#">Argentina</a> </li>
                        <li> <a href="#">Brazil</a> </li>
                        <li> <a href="#">Bolívia</a></li>
                        <li> <a href="#">Chile</a> </li>
                        <li> <a href="#">Colombia</a></li>
                        <li> <a href="#">Ecuador</a></li>
                        <li> <a href="#">Paraguay</a></li>
                        <li> <a href="#">Peru</a></li>
                        <li> <a href="#">Uruguay</a></li>
                        <li> <a href="#">Venezuela</a></li>
                    </ul>
                </div> 

                <div class="nav-column">
                    <h3>africa</h3>
                    <ul>
                        <li> <a href="#">Egypt</a></li>
                        <li> <a href="#">Morocco</a> </li>                                                        
                        <li> <a href="#">Namibia</a></li>                            
                        <li> <a href="#">South Africa</a></li>
                        <li> <a href="#">Tunisia</a> </li>
                        <li> <a href="#">Tanzania</a></li>
                        <li> <a href="#">Zambia</a></li>
                    </ul>                        
                </div>

                  <div class="nav-column">
                     <h3>asia</h3>
                    <ul>
                        <li> <a href="#">Bangladesh</a></li>
                        <li> <a href="#">Cambodia</a></li>
                        <li> <a href="#">China</a></li>
                        <li> <a href="#">India</a> </li>
                        <li> <a href="#">Indonesia</a></li>
                        <li> <a href="#">Japan</a></li> 
                        <li> <a href="#">Laos</a></li>
                        <li> <a href="#">Myanmar</a></li>
                        <li> <a href="#">Nepal</a></li>
                        <li> <a href="#">Singapore</a></li>
                        <li> <a href="#">Thailand</a></li>
                        <li> <a href="#">Tanzania</a></li>
                        <li> <a href="#">Uzbekistan</a></li>
                        <li> <a href="#">Vietnam</a> </li>

                    </ul>                                 

                    <h3>oceania</h3>
                    <ul>
                        <li> <a href="#">Australia</a></li>
                        <li> <a href="#">New Zealand</a> </li>                                                        

                    </ul>
                </div>

                </div>   
            </li>

            <li><a href="#about">about</a></li>
            <li><a href="#contact">contact</a></li>
        </ul>         
</div>


    <section id="galeria">
        <img class="slider fade" src="images/Flam Railway_small.jpg" alt=""/>
        <img class="slider fade" src="images/rocky-mountaineer.jpg" alt="" title="Rocky Mountaineer"/>
        <img class="slider fade" src="images/Hogwarts train.png" alt=""/>
        <img class="slider fade" src="images/amtrak-starlight_small.jpg" alt=""/>
        <img class="slider fade" src="images/hiram_bingham_720.jpg" alt=""/>
        <img class="slider fade" src="images/rovos rail.jpg" alt=""/>
        <img class="slider fade" src="images/Venice Simplon.jpg" alt=""/>
        <img class="slider fade" src="images/the ghan.jpg" alt=""/>

        <span id="prev">&laquo;</span>
        <span id="next">&raquo;</span>
    </section>      

    <section id="about">            

        <br>            
        <div id="aboutArticle">
        <h3>Discover the world's greatest train journeys</h3>                
        <p id="p1">                
            Ever wondered where a train can take you, besides getting you to your workplace (if that's the case) ? <br><br>
            There is another side of the story...across our beloved planet Earth, several trains meander through
            viaducts, rivers, tunnels, glaciers and fjords, where beauty meets the eye. <br><br>
            Several scenic train journeys can be found in every continent and that's what this site is all about...to showcase
            every journey with a detailed description about it's points of interest, what to expect, what to see and guide
            you through the magnificent views you will come across while looking through the window...<br><br> 

            So, why not take a vacation in Switzerland and get on the Glacier Express? <br>
            Or cross Asia in the Trans-Siberian train? <br>
            Ever heard of the Blue train or the Rovos rail, two magnificent african journeys? <br>
            Or even the Flam Railway in Norway?<br><br>

            Get on board and discover what a scenic train journey can offer you...the possibility to travel
            several miles, while watching the beautiful landscapes go by. <br><br>
            There's no other form of transportation that can offer travelling through majestic, inaccessible places.
            <br>                
        </p>            
        </div>            
    </section>

    <br>
    <br>

    <section id="contact">          
        <div id="contactForm">
            <h3>Contact Us</h3>
            <p>
                If you wish to contact us about linking your site, copyright issues, feedback, errors on the website or any 
                other issue, please send us a message using the form below.<br>
                We appreciate your contact in helping us improve your navigation experience. 
            </p>


            <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>
        </div>            
    </section>

    <section id="footer">
        <p>
        O Lorem Ipsum é um texto modelo da indústria tipográfica e de impressão. 
        O Lorem Ipsum tem vindo a ser o texto padrão usado por estas indústrias 
        desde o ano de 1500, quando uma misturou os caracteres de um texto para
        criar um espécime de livro. Este texto não só sobreviveu 5 séculos,
        mas também o salto para a tipografia electrónica, mantendo-se
        essencialmente inalterada. Foi popularizada nos anos 60 com a disponibilização
        das folhas de Letraset, que continham passagens com Lorem Ipsum, e mais
        recentemente com os programas de publicação como o Aldus PageMaker que
        incluem versões do Lorem Ipsum.
        </p>
    </section>

    <br>
    <br>
    <br>
    <br>
    <br>
</body>
</html>

And in form.php I validate input and insert into the database using prepared statements. It turns out that the error variables $ nameError, $ emailError, $ topicError, and $ msgError in index.php, do not show the messages to the user. The only message that appears is that these variables are not defined but this is easy to solve by declaring them in index.php but this is not what I want because I can undo the error of "undefined variable" although without doing the validation of form fields.

Here is the code for form.php

<?php


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

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

$nameError = "";
$emailError = "";
$topicError = "";
$msgError = "";

if( !empty( $_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();

I've tried using the superglobal $ _SESSION to pass variables but it did not work.

What method can I use to do this form validation?

    
asked by anonymous 11.01.2017 / 16:44

1 answer

2

Some problems encountered:

  • The action of your form is pointing to another file, so PHP leaves the file index.php and calls the file php/form.php , the latter does not contain the form, so it would not display the messages: / p>

    action="php/form.php"
    

    I changed it to a blank value, which means that when I post the form, the data will be posted to the index.php file again because it contains the form.

    action=""
    

    That way, there will be no error, however nothing will be processed, as you have not yet done INCLUDE/REQUIRE to the form file.

  • Make REQUIRE/INCLUDE to form:

    If the files index.php and form.php are in the same folder, simply add the line to the file index.php :

    <?php require_once 'form.php'; ?>

    If the files index.php and form.php do not are in the same folder, add the line in the file index.php , INFORMING THE FOLDER IN WHICH THE FILE is form.php , example, if the form.php file is in the php folder, which is inside the folder where the index.php file is located:

    <?php require_once './php/form.php'; ?>

  • Set the form.php file to only query the value of the $_POST array and only connect to the database if the form has been posted (see file posted below).

  • Set the index.php file to display the error messages and keep the values of the fields that have no error (see file posted below).

  • E-mail validation was incorrect:

    } elseif (filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $emailError = "Please insert a correct email address";
    }
    

    To indicate an error in the email, the test should be:

    (filter_var($email, FILTER_VALIDATE_EMAIL) === false)
    

    or

    (!filter_var($email, FILTER_VALIDATE_EMAIL))
    

Below the corrected files, considering that the two files are in the same folder (if they are not, you will need to change the path in% with%):

index.php

<!DOCTYPE html>

<html>
    <head>
        <title>Great Train Journeys</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-    scale=1.0">
        <link rel="stylesheet" href="css/style.css">
        <script src="js/jquery-3.1.0.min.js" type="text/javascript"></script>
        <script src="js/scripts.js" type="text/javascript"></script>
    </head>
    <body>

        <div id="container">
            <ul class="nav">
                <li><a href="index.php">home</a></li> 

                <li>
                    <a href="#">destinations</a>
                    <div>    
                        <div class="nav-column">                        
                            <h3>uk & ireland</h3>

                            <ul>
                                <li> <a href="#">England</a> </li>
                                <li> <a href="#">Ireland</a> </li>
                                <li> <a href="#">Scotland</a> </li>
                                <li> <a href="#">Wales</a> </li>
                            </ul>


                            <h3>mainland europe</h3>
                            <ul>
                                <li> <a href="#">Austria</a> </li>
                                <li> <a href="#">Belgium</a> </li>
                                <li> <a href="#">Bosnia & Herzegovina</a> </li>
                                <li> <a href="#">Bulgaria</a> </li>
                                <li> <a href="#">Croatia</a> </li>
                                <li> <a href="#">Czech Republic</a> </li>
                                <li> <a href="#">Denmark</a> </li>
                                <li> <a href="#">Estonia</a> </li>
                                <li> <a href="#">Finland</a> </li>
                                <li> <a href="#">France</a> </li>
                                <li> <a href="#">Germany</a> </li>
                                <li> <a href="#">Greece</a> </li>
                                <li> <a href="#">Hungary</a> </li>
                                <li> <a href="#">Italy</a> </li>
                                <li> <a href="#">Latvia</a> </li>
                                <li> <a href="#">Lithuania</a> </li>
                                <li> <a href="#">Luxembourg</a> </li>
                            </ul>
                        </div>

                        <div class="nav-column">
                            <h3>mainland europe cont...</h3>
                            <ul>                                                                                                               
                                <li> <a href="#">Macedonia</a> </li>
                                <li> <a href="#">Montenegro</a> </li>
                                <li> <a href="#">Norway</a> </li>
                                <li> <a href="#">Poland</a> </li>
                                <li> <a href="#">Portugal</a> </li>
                                <li> <a href="#">Roménia</a> </li>
                                <li> <a href="#">Russia</a> </li>
                                <li> <a href="#">Serbia</a> </li>
                                <li> <a href="#">Slovakia</a> </li>
                                <li> <a href="#">Slovenia</a> </li>
                                <li> <a href="#">Spain</a> </li>
                                <li> <a href="#">Sweden</a> </li>
                                <li> <a href="#">Switzerland</a> </li>
                                <li> <a href="#">The Netherlands</a> </li>
                                <li> <a href="#">Turkey</a> </li>
                                <li> <a href="#">Ukraine</a> </li>
                            </ul>
                        </div>

                        <div class="nav-column">
                            <h3>north america</h3>
                            <ul>
                                <li> <a href="#">Alaska</a> </li>
                                <li> <a href="#">Canada</a> </li>
                                <li> <a href="#">Mexico</a> </li>
                                <li> <a href="#">United States</a> </li>
                            </ul>                     

                            <h3>central america</h3>
                            <ul>
                                <li> <a href="#">Guatemala</a> </li>
                                <li> <a href="#">Costa Rica</a> </li>
                                <li> <a href="#">Cuba</a> </li>
                                <li> <a href="#">Panama</a> </li>
                                <li> <a href="#">St Kitts and Nevis</a> </li>
                            </ul>                 

                            <h3>south america</h3>
                            <ul>
                                <li> <a href="#">Argentina</a> </li>
                                <li> <a href="#">Brazil</a> </li>
                                <li> <a href="#">Bolívia</a></li>
                                <li> <a href="#">Chile</a> </li>
                                <li> <a href="#">Colombia</a></li>
                                <li> <a href="#">Ecuador</a></li>
                                <li> <a href="#">Paraguay</a></li>
                                <li> <a href="#">Peru</a></li>
                                <li> <a href="#">Uruguay</a></li>
                                <li> <a href="#">Venezuela</a></li>
                            </ul>
                        </div> 

                        <div class="nav-column">
                            <h3>africa</h3>
                            <ul>
                                <li> <a href="#">Egypt</a></li>
                                <li> <a href="#">Morocco</a> </li>                                                        
                                <li> <a href="#">Namibia</a></li>                            
                                <li> <a href="#">South Africa</a></li>
                                <li> <a href="#">Tunisia</a> </li>
                                <li> <a href="#">Tanzania</a></li>
                                <li> <a href="#">Zambia</a></li>
                            </ul>                        
                        </div>

                        <div class="nav-column">
                            <h3>asia</h3>
                            <ul>
                                <li> <a href="#">Bangladesh</a></li>
                                <li> <a href="#">Cambodia</a></li>
                                <li> <a href="#">China</a></li>
                                <li> <a href="#">India</a> </li>
                                <li> <a href="#">Indonesia</a></li>
                                <li> <a href="#">Japan</a></li> 
                                <li> <a href="#">Laos</a></li>
                                <li> <a href="#">Myanmar</a></li>
                                <li> <a href="#">Nepal</a></li>
                                <li> <a href="#">Singapore</a></li>
                                <li> <a href="#">Thailand</a></li>
                                <li> <a href="#">Tanzania</a></li>
                                <li> <a href="#">Uzbekistan</a></li>
                                <li> <a href="#">Vietnam</a> </li>

                            </ul>                                 

                            <h3>oceania</h3>
                            <ul>
                                <li> <a href="#">Australia</a></li>
                                <li> <a href="#">New Zealand</a> </li>                                                        

                            </ul>
                        </div>

                    </div>   
                </li>

                <li><a href="#about">about</a></li>
                <li><a href="#contact">contact</a></li>
            </ul>         
        </div>


        <section id="galeria">
            <img class="slider fade" src="images/Flam Railway_small.jpg" alt=""/>
            <img class="slider fade" src="images/rocky-mountaineer.jpg" alt="" title="Rocky Mountaineer"/>
            <img class="slider fade" src="images/Hogwarts train.png" alt=""/>
            <img class="slider fade" src="images/amtrak-starlight_small.jpg" alt=""/>
            <img class="slider fade" src="images/hiram_bingham_720.jpg" alt=""/>
            <img class="slider fade" src="images/rovos rail.jpg" alt=""/>
            <img class="slider fade" src="images/Venice Simplon.jpg" alt=""/>
            <img class="slider fade" src="images/the ghan.jpg" alt=""/>

            <span id="prev">&laquo;</span>
            <span id="next">&raquo;</span>
        </section>      

        <section id="about">            

            <br>            
            <div id="aboutArticle">
                <h3>Discover the world's greatest train journeys</h3>                
                <p id="p1">                
                    Ever wondered where a train can take you, besides getting you to your workplace (if that's the case) ? <br><br>
                    There is another side of the story...across our beloved planet Earth, several trains meander through
                    viaducts, rivers, tunnels, glaciers and fjords, where beauty meets the eye. <br><br>
                    Several scenic train journeys can be found in every continent and that's what this site is all about...to showcase
                    every journey with a detailed description about it's points of interest, what to expect, what to see and guide
                    you through the magnificent views you will come across while looking through the window...<br><br> 

                    So, why not take a vacation in Switzerland and get on the Glacier Express? <br>
                    Or cross Asia in the Trans-Siberian train? <br>
                    Ever heard of the Blue train or the Rovos rail, two magnificent african journeys? <br>
                    Or even the Flam Railway in Norway?<br><br>

                    Get on board and discover what a scenic train journey can offer you...the possibility to travel
                    several miles, while watching the beautiful landscapes go by. <br><br>
                    There's no other form of transportation that can offer travelling through majestic, inaccessible places.
                    <br>                
                </p>            
            </div>            
        </section>

        <br>
        <br>

        <section id="contact">          
            <div id="contactForm">
                <h3>Contact Us</h3>
                <p>
                    If you wish to contact us about linking your site, copyright issues, feedback, errors on the website or any 
                    other issue, please send us a message using the form below.<br>
                    We appreciate your contact in helping us improve your navigation experience. 
                </p>

                <?php require_once 'form.php'; ?>
                <form id="form" name="contactForm" method="post" action="">
                    <div>
                        <label for="name">Your name</label> 
                        <input type="text" id="name" name="name" maxlength="40" placeholder="Write your Name" value="<?php echo isset($name) ? $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]" 
                               value="<?php echo isset($email) ? $email : ''; ?>">
                        <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"  
                            <?php echo isset($topic) ? ($topic == 'copyright' ? 'selected' : '') : ''; ?>
                                    >Copyright</option>
                            <option value="errors" 
                            <?php echo isset($topic) ? ($topic == 'errors' ? 'selected' : '') : ''; ?>
                                    >Site/Article errors</option>
                            <option value="feedback"
                            <?php echo isset($topic) ? ($topic == 'feedback' ? 'selected' : '') : ''; ?>
                                    >Feedback</option>
                            <option value="other"
                            <?php echo isset($topic) ? ($topic == 'other' ? 'selected' : '') : ''; ?>
                                    >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"><?php echo isset($msg) ? $msg : ''; ?></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>
            </div>            
        </section>

        <section id="footer">
            <p>
                O Lorem Ipsum é um texto modelo da indústria tipográfica e de impressão. 
                O Lorem Ipsum tem vindo a ser o texto padrão usado por estas indústrias 
                desde o ano de 1500, quando uma misturou os caracteres de um texto para
                criar um espécime de livro. Este texto não só sobreviveu 5 séculos,
                mas também o salto para a tipografia electrónica, mantendo-se
                essencialmente inalterada. Foi popularizada nos anos 60 com a disponibilização
                das folhas de Letraset, que continham passagens com Lorem Ipsum, e mais
                recentemente com os programas de publicação como o Aldus PageMaker que
                incluem versões do Lorem Ipsum.
            </p>
        </section>

        <br>
        <br>
        <br>
        <br>
        <br>
    </body>
</html>

File form.php

<?php

$nameError = "";
$emailError = "";
$topicError = "";
$msgError = "";

if (!empty($_POST['submit'])) { // SE FOI POSTADO
    // só existem se foi postado
    $name = $_POST['name'];
    $email = $_POST['user_mail'];
    $topic = $_POST['topic'];
    $msg = $_POST['user_message'];

    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) === false) {
        $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";
    }


    // só precisa conectar se foi postado
    $servername = "localhost:3306";
    $username = "root";
    $password = "";
    $dbname = "site_comboios";
    //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();
}

Result: Print with the result after posting the form:

    
11.01.2017 / 17:10