php 如果数据库连接失败,则 AJAX POST响应返回empy

yqkkidmi  于 2023-06-28  发布在  PHP
关注(0)|答案(1)|浏览(125)

我正在构建一个PHP项目,它有一个简单的表单,包含3个字段。此表单与名为“article”的MySQL表连接。当我提交表单时,在jQuery和 AJAX 的帮助下,我显示了一条通知消息:例如,成功提交时显示“已成功提交”或失败提交时显示“出现问题”。我的问题是,这个通知消息在成功提交时工作正常,但如果有错误-例如,如果数据库连接失败-那么通知消息是空的,它不显示错误消息!我在代码中添加了console.log(error);,这样我就可以检查控制台是否有错误,但那里没有显示错误。我做错了什么?
下面是我为在DB中提交表单而编写的PHP代码:

<?php
require __DIR__ . '/../config_db.php';

if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Retrieve the submitted values
$article = $_POST["article"];
$author = $_POST["author"];
$tags = $_POST["tags"];

// Create a new database connection
$connection = new mysqli($servername, $username, $password, $dbname);

// Check the connection
if ($connection->connect_error) {
    $response = array(
        "status" => "error",
        "message" => "Error: Failed to connect to the database."
    );
} else {
    // Prepare the statement
    $stmt = $connection->prepare("INSERT INTO article (article, author, tags) VALUES (?, ?, ?)");

    // Bind parameters to the statement
    $stmt->bind_param("sss", $article, $author, $tags);

    if ($stmt->execute()) {
        $response = array(
            "status" => "success",
            "message" => "Article submitted successfully!"
        );
    } else {
        $response = array(
            "status" => "error",
            "message" => "Error: " . $stmt->error
        );
    }

    // Close the statement
    $stmt->close();
    
    // Close the database connection
    $connection->close();
}

// Send the JSON response
header('Content-Type: application/json');
echo json_encode($response);
}
?>

下面是 AJAX 的html表单:

<form method="post" action="submit_article.php" id="articleForm">
            <div class="field">
                <div class="control">
                    <textarea class="textarea" id="article" name="article" placeholder="Enter the article..." required></textarea>
                </div>
            </div>

            <div class="field">
                <div class="control">
                    <input class="input" type="text" id="author" name="author" placeholder="Author name..." required>
                </div>
            </div>

            <div class="field">
                <div class="control">
                    <input class="input" type="text" id="tags" name="tags" placeholder="Add some tags...">
                </div>
            </div>

            <div class="field is-grouped">
                <div class="control">
                    <input class="button is-link" type="submit" value="Submit">
                </div>
                <div class="control">
                    <input class="button is-link is-light" type="button" value="Cancel" onclick="window.location.href='index.php'">
                </div>
            </div>
        </form>
 <div id="notification" class="notification is-primary"></div>

 <script>
    $(document).ready(function() {
        $("#articleForm").submit(function(e) {
            e.preventDefault(); // Prevent form submission

            // Send the form data via AJAX
            $.ajax({
                url: "submit_article.php",
                type: "POST",
                data: $(this).serialize(),
                success: function(response) {
                    // Display the notification message
                    var notification = $("#notification");
                    notification.text(response['message']);
                    notification.fadeIn().delay(3000).fadeOut();

                    // Clear the form
                    $("#article").val("");
                    $("#author").val("");
                    $("#tags").val("");
                },
                error: function(xhr, status, error) {
                    // Display the error message
                    var notification = $("#notification");
                    notification.text(response['message']);
                    notification.fadeIn().delay(3000).fadeOut();
                    console.log(error); // Log any errors to the console
                }
            });

            return false; // Prevent default form submission
        });
    });
</script>
elcex8rz

elcex8rz1#

使用$connection->connect_error会给予你一个众所周知的错误,如错误的用户/密码/权限等.
真实的的连接问题会导致new mysqli($servername, $username, $password, $dbname);抛出异常。因此,您的脚本只是被通用异常处理程序中断,并且由于$connection->connect_error而生成的错误响应将永远不会生成。
为了覆盖这一点,您需要使用try/catch-block并在那里生成适当的响应。
更新:使用mysqli_report(MYSQLI_REPORT_STRICT);,你可以强制mysqli抛出已知错误的异常-然后你可以省略额外的If检查并处理catch块中的所有内容。

相关问题