提交表格时成功或失败的信息

时间:2017-12-20 03:32:36

标签: php html mysql

我刚刚进入HTML和PHP。我目前正在开发一个联系页面,它接受用户输入并将数据放在我给定的数据库中。除了提交表单时的成功和失败消息之外,我已设法让一切工作正常。我试图使用PHP'if'和'else'语句将成功或失败消息显示在同一页面上。请注意,我已设法在标题中显示成功或失败的消息。

我做了大量的研究,并遇到了一些类似的问题。但是,似乎都没有效果。如果有人能看看我的代码,我将不胜感激;也许会指引我朝着正确的方向前进提前致谢。

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代码:

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

2 个答案:

答案 0 :(得分:0)

您可以执行发送$_GET查询的内容(例如contact.php?response=whatever),但是您需要检查该内容而不是$_POST。另一种方法是将消息存储在会话中并在原始页面上调用它们。另请注意,您需要在查询中绑定参数,转义是passé而不是绑定参数的安全性。如果您还没有这样做,我会使用配置文件并将其包含在每个顶级页面的顶部。此外,我在这里提出两件事,1)使用框架或2)学习如何在类/方法场景中执行这些功能,以获得OOP(面向对象编程)的全部好处。最后,我还没有测试过这个,所以记住这一点,但它应该可行,只要我没有语法错误。

/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>';

答案 1 :(得分:0)

我已对 html 代码进行了更改,将$_POST替换为$_REQUEST

这是您更新的代码:

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代码:

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