Pass error variables between two php files

Asked

Viewed 42 times

3

Hello

I am trying to validate a form in different files, but I cannot 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 php form. I validate the inputs and insert them 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 that’s not what I want, because I can thus undo the error of "Undefined variable" although without validating the form fields.

Here is the code of php form.

<?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 $_SESSION superglobal to pass variables but it didn’t work.

What method can I use to perform this form validation?

  • used Session like this ? $_SESSION['error'] = 'error message'

1 answer

2


Some problems found:

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

    action="php/form.php"
    

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

    action=""
    

    This way, there will be no error, but nothing will be processed, because you have not done the INCLUDE/REQUIRE for the form file.

  • Do REQUIRE/INCLUDE for the form:

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

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

    If the files index.php and form.php NAY 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 file form.php is in the folder php, which is inside the folder where the file is located index.php:

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

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

  • Adjust the file index.php to display the error messages and maintain 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 are in the same folder (if they are not, it will be necessary to change the path in require_once):

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>

Filing cabinet php form.

<?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();
}

Upshot: Screen print with result after posting the form: inserir a descrição da imagem aqui

  • Hi Allan. It’s not there because I had already put the form.php in the action attribute of the form. However I tested your suggestion in it and I ended up having "Undefined index" errors (the variables $name, $email, $topic and $msg are not calling the respective attribute)

  • I have updated. I await the result of your simulation.

  • I updated my answer, hope it will be useful to help you solve your problem. Good luck!

  • Dear @Allan . Thank you so much for your help, so I managed to "jump the wall". However only one aside regarding data security...there is php code in index.php that will be visible to a possible attacker...given that I am entering data through Prepared statements, will I have high security? I ask only to have a real notion of this kind of problems. However I will continue with the rest of the form since it still lacks some adjustments. Thank you again.

  • Talking about HIGH security is very relative. There are reports from security companies that belong to famous hackers and that these companies have been hacked. In your case, I think in terms of safety you’re satisfactory.

Browser other questions tagged

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