将文本字段保存到MySQL数据库

时间:2019-07-25 18:12:53

标签: javascript php ajax twitter-bootstrap-3

@编辑2

我认为问题出在争执。

<br />
<b>Warning</b>:  mysqli_connect(): (HY000/2002): Connection refused in <b>/opt/lampp/htdocs/ch1/saveEmail.php</b> on line <b>12</b><br />
Failed to connect to MySQL: Connection refused<br />
<b>Warning</b>:  mysqli_query() expects parameter 1 to be mysqli, bool given in <b>/opt/lampp/htdocs/ch1/saveEmail.php</b> on line <b>30</b><br />
<br />
<b>Warning</b>:  mysqli_close() expects parameter 1 to be mysqli, bool given in <b>/opt/lampp/htdocs/ch1/saveEmail.php</b> on line <b>41</b><br />

@Edit ,如果我禁用doRecord方法并为$retVal分配了一个随机数,则可以从控制台中看到其值。我认为问题出在功能的主体上。


我正在尝试将字段输入的信息保存到MySQL数据库中。但是我什至看不到exit(json_encode(array("response" => $response)));exit(json_encode(array("response" => "not entered")));的结果。经过测试,我确定数据库可以正常工作。此外,按钮onclick可以使用,但不能再使用了。怎么了?

saveEmail.php

<?php


function doRecord($host, $username, $password, $dbName,
                  $senderName, $senderMail, $senderSubject, $senderBody, $cronInput) {

    $retVal = 0;
    /* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
    $link = new mysqli($host, $username, $password, $dbName);

// Check connection
    if($link === false){
        die("ERROR: Could not connect. " . mysqli_connect_error());
    }

    $date = gmdate('Y-m-d h:i:s', time());
    /*$htmlBody =
        "bodyy <p><a href=\"http://sdfdsf.com/\" target=\"_blank\" rel=\"noopener\">link burada</a>&nbsp;</p>
    <p>&nbsp;</p>
    <p>fdgfd</p>";
    */


// Attempt insert query execution
    $sql = "INSERT INTO  staj.info(name, email, subject, body, progressTime, cronInput)
            VALUES
    ('$senderName', '$senderMail', '$senderSubject', '$senderBody', '$date', '$cronInput');";


    if(mysqli_query($link, $sql)){
        //echo "Records inserted successfully.";
        $retVal = 1;
    } else{
        //echo "\n\nERROR: Could not able to execute $sql. " . mysqli_error($link);
        $retVal = 0;
    }



// Close connection
    mysqli_close($link);
    return $retVal;
}

if (isset($_POST['cron'])) {
    $name = $_POST['name'];
    $email = $_POST['email'];
    $subject = $_POST['subject'];
    $body = $_POST['body'];
    $cron = $_POST['cron'];



    $retVal = doRecord("127.0.0.1", "root", "12345678", "staj",
        $name, $email, $subject, $body, $cron);



    if ($retVal == 1) {
        $response = "Mail is put into database";
    } else {
        $response = "SQL error.";
    }
    exit(json_encode(array("response" => $response)));
} else {
    exit(json_encode(array("response" => "not entered")));
}


?>

index.php

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>

    <link href="http://netdna.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.css" rel="stylesheet">
    <link href="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.12/summernote.css" rel="stylesheet">

    <style type="text/css">
        textarea, input {
            margin-bottom: 10px;
        }

    </style>

</head>
<body>
    <div class="container" style="margin-top:100px;">
        <div class="row justify-content-center">
            <div class="col-md-6 col-md-offset-3">
                <label for="name">Name:</label>
                <input id="name" placeholder="Name" class="form-control" required>

                <label for="email">E-mail:</label>
                <input id="email" placeholder="E-mail" class="form-control" required>

                <label for="subject">Subject:</label>
                <input id="subject" placeholder="Name" class="form-control" required>

                <!--<label for="body">Body:</label>-->
                <textarea id="summernote" placeholder="Email body" name="editordata"></textarea>


                <label for="cron">Crontab:</label>
                <input id="cron" placeholder="CronTab Input" class="form-control">

                <input type="button" onclick="saveMail()" value="Save it to Database" class="btn btn-success btn-info">
            </div>
        </div>
    </div>


<script
        src="https://code.jquery.com/jquery-3.4.1.js"
        integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="
        crossorigin="anonymous"></script>

<script type="text/javascript">
    function isNotEmpty(caller) {
        if (caller.val() == "") {
            caller.css('border', '1px solid red');
            return false;
        } else {
            caller.css('border', '');
            return true;
        }
    }

    function saveMail() {
        console.log("SaVinG Attempt...");
        var name = $("#name");
        var email = $("#email");
        var subject = $("#subject");
        var body = $("#summernote");
        var cron = $("#cron");

        if (isNotEmpty(cron)) {
            $.ajax({
                url: 'saveEmail.php',
                method: 'POST',
                dataType: 'json',
                data: {
                    name: name.val(),
                    email: email.val(),
                    subject: subject.val(),
                    body: body.val(),
                    cron: cron.val()
                }, success: function (response) {
                    console.log(response);
                }
            });
        }
    }   
</script>

<!-- WYSIWYG editor jses -->
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.12/summernote.js"></script>
<script>
    $(document).ready(function() {
        $('#summernote').summernote({
            height: 300,
            focus: true
        });
    });
</script>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

似乎您的saveEmail.php文件中的引号不正确。如果使用代码突出显示,则更容易看到。代替:

exit(json_encode(array("response" => "not entered”)));

尝试:

exit(json_encode(array("response" => "not entered")));

编辑:

要查看哪种错误阻止了您的AJAX调用,请将这些调用行放在saveEmail.php的开头:

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

然后暂时将ajax调用更改为如下形式:

$.ajax({
url: 'saveEmail.php',
method: 'POST',
data: {
    name: name.val(),
    email: email.val(),
    subject: subject.val(),
    body: body.val(),
    cron: cron.val()
}, success: function (response) {
   console.log(response);
} });
相关问题