php - 提交表格时的成功或失败消息

标签 php html mysql

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

我做了很多研究,也遇到过一些类似的问题。然而,似乎没有一个起作用。如果有人能看一下我的代码,我将不胜感激;也许引导我走向正确的方向。提前致谢。

HTML 代码:

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

最佳答案

您可以执行您所做的操作,即发回 $_GET 查询(例如 contact.php?response=whatever),但随后您需要检查该查询$_POST。另一种方法是将消息存储在 session 中并在原始页面上调用它们。另请注意,您需要在查询上绑定(bind)参数,转义已经过时,并且不如绑定(bind)参数那么安全。如果您还没有这样做,我将使用配置文件并将其包含在每个顶级页面的顶部。另外,我在这里建议两件事,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>';

关于php - 提交表格时的成功或失败消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47898391/

相关文章:

linux - PHP fopen "failed to open stream: resource temporarily unavailable"

html - 使用 iframe 作为链接?

javascript - 如何在SMOKE js验证插件中添加自定义规则?

php - php中fpdf的utf8解码

Mysql Groupby和Orderby问题

php - 显示一个 jQuery 对话框/弹出窗口,然后使用对话框的结果设置一个隐藏字段

PHP - 如何用空格替换破折号?

MySQL查询难度

php - CakePHP 应用程序在生产中指向 lib/Cake/Console/Templates/skel/View/Pages/home.ctp

jquery - 如何将子菜单添加到下拉菜单