简体   繁体   中英

success or fail message upon submitting the form

I have just got into HTML and PHP. I am currently working on a contact page that takes user input and places the data in my given database. I have managed to get everything to work, besides the success and fail message upon submitting the form. I am trying to get the success or fail message to display on the same page using PHP 'if' and 'else' statement. Note that I have managed to display the success or fail messege in the header.

I have done a great deal of research, and have come across some similar issues. However, none seem to work. I would be grateful if anyone can take a look at my code; and perhaps direct me in the right direction. Thanks in advance.

HTML code:

<section class="main-container">
<div class="main-wrapper">
    <h2>Contact Us</h2>
    <form class="signup-form" action="includes/contact.inc.php" method="POST">       
        <input type="text"  name="user_fullname"    required placeholder="Fullname">
        <input type="email" name="user_email"   required placeholder="E-mail">
        <input type="text"  name="subject" required placeholder="Subject">
        <input type="text"  name="message" style="height:250px;" required placeholder="Message">
        <button type="submit" name="submit">Submit</button>
    </form>
</div>
</section>

<?php
    if (isset($_POST['submit'])) {
        echo "Contact Successful!";
    } else {
        echo "Contact Fail!";   
    }           
?>

PHP code:

<?php

if (isset($_POST['submit'])) {

    include_once 'dbh.inc.php';

    $fullname  = mysqli_real_escape_string($conn, $_POST['user_fullname']);
    $email     = mysqli_real_escape_string($conn, $_POST['user_email']);
    $subject   = mysqli_real_escape_string($conn, $_POST['subject']);
    $message   = mysqli_real_escape_string($conn, $_POST['message']);


    if (!preg_match("/^[a-zA-Z]*$/", $fullname)) {
        header("Location: ../contact.php?contact details=invalid");
        exit(); 
    } else {
        $sql = "INSERT INTO contact (user_fullname, user_email, subject, message) VALUES ('$fullname', '$email', '$subject', '$message');";
        mysqli_query($conn, $sql);
        header("Location: ../contact.php?contact=success");     
        exit();
    }
} else {
    header("Location: ../contact.php");
    exit();
}

You can do what you did which is send back a $_GET query (like contact.php?response=whatever ) but then you need to check for that instead of $_POST . The alternative to that is to store the messages in the session and recall them on the original page. Also note, you need to bind parameters on your query, the escaping is passé and not as secure as binding parameters. If you don't already do so, I would employ the use of a config file and include it on the top of every top-level page. Also, I would propose two things here, 1) use a framework or 2) learn how to do these functions in a class/method scenario to get the full benefits of OOP (object oriented programming). Finally, I have not tested any of this, so keep that in mind, but it should work, provided I have no syntax errors.

/config.php

<?php
# Create some defines for consistent file reference
define('DS',DIRECTORY_SEPARATOR);
define('ROOT_DIR',__DIR__);
define('INCLUDES',ROOT_DIR.DS.'includes');
define('FUNCTIONS',INCLUDES.DS.'functions');
# Start session
session_start();
# Add database
include_once(INCLUDES.DS.'dbh.inc.php');

/includes/functions/myfunctions.php

<?php
function insertMessage($conn,$fullname,$email,$subject,$message)
{
    # You need to bind parameters here, forget about the escaping business
    $sql = "INSERT INTO contact (user_fullname, user_email, subject, message) VALUES (?,?,?,?)";
    # Prepare
    $stmt  = mysqli_prepare($conn, $sql);
    # Bind the parameters
    mysqli_stmt_bind_param($stmt, 'ssss', $fullname,$email,$subject,$message);
    # Execute the query
    mysqli_stmt_execute($stmt);
    mysqli_stmt_close($stmt);
}

function setMessage($msg,$type)
{
    # Store the message to session
    $_SESSION['messages'][$type] = $msg;
}

function getMessage($type=false)
{
    # If there is no specific type to return, send all messages
    if(empty($type)) {
        if(isset($_SESSION['messages'])) {
            $msgs = $_SESSION['messages'];
            unset($_SESSION['messages']);
            return $msgs;
        }
        # Return false by default
        return false;
    }
    # To send a specific message, try retrieving $type
    if(isset($_SESSION['messages'][$type])) {
        $msg = $_SESSION['messages'][$type];
        unset($_SESSION['messages'][$type]);
        return $msg;
    }
    # Return false by default
    return false;
}

/includes/contact.inc.php

# Include our defines, session, database
include_once('..'.DIRECTORY_SEPARATOR.'config.php');
# Add our functions
include_once(FUNCTIONS.DS.'myfunctions.php');
# Check if the submission is set
if(isset($_POST['submit'])) {
    # Check if the name and email are valid
    if(!preg_match("/^[a-zA-Z]*$/", $_POST['user_fullname']) || !filter_var($_POST['user_email'],FILTER_VALIDATE_EMAIL)) {
        # If not valid, save message to session
        setMessage('Invalid email or name.','error');
    } else {
        # Insert the message into the database
         insertMessage($conn,$_POST['user_fullname'],$_POST['user_email'],$_POST['subject'],$_POST['message']);
        # Store the message for writing back
        setMessage('Thank you, your message has been sent.','success');
    }
}
# Redirect
header("Location: ../contact.php");
exit;

/contact.php

<?php
# Include our defines, session, database
include_once('config.php');
# Add our functions
include_once(FUNCTIONS.DS.'myfunctions.php');
?>
<section class="main-container">
<div class="main-wrapper">
    <h2>Contact Us</h2>
    <form class="signup-form" action="includes/contact.inc.php" method="POST">       
        <input type="text"  name="user_fullname"    required placeholder="Fullname">
        <input type="email" name="user_email"   required placeholder="E-mail">
        <input type="text"  name="subject" required placeholder="Subject">
        <input type="text"  name="message" style="height:250px;" required placeholder="Message">
        <button type="submit" name="submit">Submit</button>
    </form>
</div>
</section>

<?php
# Fetch all messages (could be error or could be success)
$msg = getMessage();
# If there are messages
if(!empty($msg))
    # Write them to the page
    echo '<div class="alerts">'.implode('</div><div class="alerts">',$msg).'</div>';

I have made changes in html code, replace $_POST with $_REQUEST .

Here is your updated code :

HTML code:

<section class="main-container">
<div class="main-wrapper">
    <h2>Contact Us</h2>
    <form class="signup-form" action="includes/contact.inc.php" method="POST">       
        <input type="text"  name="user_fullname"    required placeholder="Fullname">
        <input type="email" name="user_email"   required placeholder="E-mail">
        <input type="text"  name="subject" required placeholder="Subject">
        <input type="text"  name="message" style="height:250px;" required placeholder="Message">
        <button type="submit" name="submit">Submit</button>
    </form>
</div>
</section>

<?php
    if (isset($_REQUEST['contact'] == "success")) {
        echo "Contact Successful!";
    } else {
        echo "Contact Fail!";   
    }           
?>

PHP code:

<?php

if (isset($_POST['submit'])) {

    include_once 'dbh.inc.php';

    $fullname  = mysqli_real_escape_string($conn, $_POST['user_fullname']);
    $email     = mysqli_real_escape_string($conn, $_POST['user_email']);
    $subject   = mysqli_real_escape_string($conn, $_POST['subject']);
    $message   = mysqli_real_escape_string($conn, $_POST['message']);


    if (!preg_match("/^[a-zA-Z]*$/", $fullname)) {
        header("Location: ../contact.php?contact=invalid");
        exit(); 
    } else {
        $sql = "INSERT INTO contact (user_fullname, user_email, subject, message) VALUES ('$fullname', '$email', '$subject', '$message');";
        mysqli_query($conn, $sql);
        header("Location: ../contact.php?contact=success");     
        exit();
    }
} else {
    header("Location: ../contact.php");
    exit();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM